Polymorphism and Encapsulation

JavaJavaBeginner
Practice Now

Introduction

Encapsulation is like a bag that encloses the operations and the data related to an object together. Polymorphism is the ability of an object to take on many forms. In this lab, you will see what they are like.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/method_overloading("`Method Overloading`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/abstraction("`Abstraction`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/constructors("`Constructors`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("`Inheritance`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/interface("`Interface`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/method_overloading -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/scope -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/inner_classes -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/abstraction -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/classes_objects -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/class_attributes -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/class_methods -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/constructors -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/encapsulation -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/inheritance -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/interface -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/modifiers -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/oop -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/identifier -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/arrays -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/booleans -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/comments -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/data_types -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/operators -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/output -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/strings -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} java/system_methods -.-> lab-178551{{"`Polymorphism and Encapsulation`"}} end

Polymorphism

Polymorphism is one of the OOP features that allows us to perform a single action in different ways. Polymorphism that is resolved during compiler time is static polymorphism or compile-time polymorphism (overloading is this type). Polymorphism that is resolved during runtime is called runtime polymorphism (overriding is this type). Polymorphism also provides the feature of an object to take on many forms. A very common use of polymorphism in OOP is when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class type or as an interface type. The case of inheritance is one form of polymorphism, because there are different kinds of animals' behaviors and animals' features. But here we introduce another form of polymorphism:

Example:

Write the following code in the /home/labex/project/polymorphismTest.java file:

// we declare an interface life, it has some methods, we just omit them.
interface life{}
// and declare a class to realize polymorphism, the inner content, we just ignore that for this case.
class Animal{}
// we declare a Human class to use class of Animal and the life interface.
class Human extends Animal implements life{}

public class polymorphismTest{
    public static void main(String[] args){
        Human human = new Human();  // instantiate a Human object
        // Human has direct or indirect inheritance relationship with Animal, Object
        // Human implements life interface, so the instanceof expression returns true
        System.out.println("human is instance of Human? " + (human instanceof Human));
        System.out.println("human is instance of Animal? " + (human instanceof Animal));
        System.out.println("human is instance of life? " + (human instanceof life));
        System.out.println("human is instance of Object? " + (human instanceof Object));
    }
}

Output:

Run the polymorphismTest.java file using the following commands:

javac /home/labex/project/polymorphismTest.java
java polymorphismTest

See the output:

human is instance of Human? true
human is instance of Animal? true
human is instance of life? true
human is instance of Object? true

Encapsulation

Encapsulation is a concept that lets us hide the details of program. Other invokers just need to know what a program can give you without knowing how it works. Encapsulation simplifies the development. It is a mechanism of wrapping the data (variables) and algorithms (method code). In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of the class. Therefore, it is also known as data hiding. Commonly, the class fields are declared private and we use getter/setter methods to access and control data. We define public methods just to provide functionalities to other classes or for outside usage. Sometimes we define private methods which are used just within the class for some specific usage. This is how we hide details.

Example:

Write the following code in the /home/labex/project/encapsulationTest.java file:

class Person{
    /*
     * there are two member variables in Person
     * they are private, so can't be accessed outside this class directly.
    */
    private String name;
    private int age;
    // empty constructor
    public Person(){

    }
    // constructor with two parameters
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    // use this method to get name value
    public String getName(){
        return this.name;
    }
    // use this method to set name value
    public void setName(String name){
        this.name = name;
    }
    // use this method to get age value
    public int getAge(){
        return this.age;
    }
    // use this method to set age value
    public void setAge(int age){
        this.age = age;
    }
}
public class encapsulationTest{
    public static void main(String[] args){
        Person p = new Person();
        // we set a person's name and age using setXXX() methods
        p.setName("Mike");
        p.setAge(20);
        // we get a person's name and age using getXXX() methods
        System.out.println("Name: " + p.getName() + ", Age: " + p.getAge());
    }
}

Output:

Run the encapsulationTest.java file using the following commands:

javac /home/labex/project/encapsulationTest.java
java encapsulationTest

See the output:

Name: Mike, Age: 20

Summary

With encapsulation, we don't need to access object data or properties directly using object.XXX, rather we use some standard method in form of getXXX(), setXXX() and other methods to do the job. In generic programming, the advantage of polymorphism will be shown, but for now you just remember that polymorphism allows an object to take on many forms.

Other Java Tutorials you may like