Inheritance and polymorphism in Java

1- Instroduction

Inheritance and polymorphism - this is a very important concept in Java. You must understand it better if you want to learn java.

2- Class, Constructor and instance

You need to understand explicitly about class, constructor and instance before starting to learn inheritance in java. We consider the class Person, describes a person with information full name, year of birth, year die.
  • Person.java
package org.o7planning.tutorial.inheritance.basic;

public class Person {

    // Field name - name of person
    private String name;

    // Field bornYear
    private Integer bornYear;

    // Field diedYear.
    private Integer diedYear;

    // Constructor with 3 parameters. The aim is to assign value for the field of Person.
    // Specify the name, year of birth, died year.
    public Person(String name, Integer bornYear, Integer diedYear) {
        this.name = name;
        this.bornYear = bornYear;
        this.diedYear = diedYear;
    }

    // Constructor with 2 parameters.
    // The aim is to assign value for the field of Person.
    // Not assign for diedYear
    public Person(String name, Integer bornYear) {
        this.name = name;
        this.bornYear = bornYear;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getBornYear() {
        return bornYear;
    }

    public void setBornYear(Integer bornYear) {
        this.bornYear = bornYear;
    }

    public Integer getDiedYear() {
        return diedYear;
    }

    public void setDiedYear(Integer diedYear) {
        this.diedYear = diedYear;
    }
}
  • PersonDemo.java
package org.o7planning.tutorial.inheritance.basic;

public class PersonDemo {

    public static void main(String[] args) {

        // Instance: Thomas Edison.
        Person edison = new Person("Thomas Edison", 1847, 1931);

        System.out.println("Info:");
        System.out.println("Name: " + edison.getName());
        System.out.println("Born Year: " + edison.getBornYear());
        System.out.println("Died Year: " + edison.getDiedYear());

        // Instance: Bill Gates
        Person billGates = new Person("Bill Gate", 1955);

        System.out.println("Info:");
        System.out.println("Name: " + billGates.getName());
        System.out.println("Born Year: " + billGates.getBornYear());
        System.out.println("Died Year: " + billGates.getDiedYear());

    }

}

Distinguishing Class,constructor and instance:

Person simulate a class of people, it is something abstract, but it has information, in the example above, information is the name, year of birth, died year.

Constructor
  • Constructor always have the same name as the class
  • One class has one or more constructors.
  • Constructor with or without parameters, no parameters constructor called default constructor.
  • Constructor using for create a instance of class.
  

See example, create a object (instance) from Constructor.

3- Inheritance in java

We need a few classes to participate in examples.
  • Animal: Class simulate an animal.
  • Duck: Subclass of Animal.
  • Cat: Subclass of Animal.
  • Mouse: Subclass of Animal.
Here we have the Animal class, it has a method without body.
  • public abstract String getAnimalName();

This method is an abstract method, in the subclass you need to declare and implement its body.

Animal class has at least one abstract method, it must be declared as abstract. Class abstract has constructor, but you can not create instance from it.
  • In essence means that you want to create an object of animal, you need to create from a specific animal species, in this case, you must create from constructor of Cat, Mouse or Duck.
  • Animal.java
package org.o7planning.tutorial.inheritance.animal;

// Class with at least one abstract method must be declared as abstract.
public abstract class Animal {

    // Name, for example, Tom Cat, Jerry Mouse.
    private String name;

    // Default constructor
    public Animal() {
        // Assign the default
        this.name = this.getAnimalName();
    }

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // Returns the name of this animal.
    // An abstract method.
    // The specific contents of this method will be written in the subclass.
    public abstract String getAnimalName();

}

Next see Cat class, inherited from Animal.

Cat also has constructor, and also has fields. In the first line of the constructor must call super(..), means that call to constructor of parent class, to assign value for fields of the parent class.

 If you do not call call super(..), java auto insert super() into first line of constructor at compile time.
  • Cat.java
package org.o7planning.tutorial.inheritance.animal;

public class Cat extends Animal {

    private int age;
    private int height;

    public Cat(int age, int height) {
        // Call the default Constructor of the parent class (Animal)
        // Aims initialize the fields in the parent class.
        super();

        // Next, Assign value to its fields
        this.age = age;
        this.height = height;
    }

    public Cat(String name, int age, int height) {
    
        // Call the default Constructor of the parent class (Animal)
        // Aims initialize the fields in the parent class.        
        super(name);

        // Next, Assign value to its fields
        this.age = age;
        this.height = height;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }


    // Implement content for abstract methods declared in the parent class.
    @Override
    public String getAnimalName() {
        return "Cat";
    }

}

When you create a Cat object, what happens?

View Mouse class, subclass of Animal.

  • Mouse.java
package org.o7planning.tutorial.inheritance.animal;

public class Mouse extends Animal {

    private int weight;

    // Default constructor
    public Mouse() {
        // Call to constructor Mouse(int)
        this(100);
    }


    // Constructor with one parameter.
    public Mouse(int weight) {
        
        // If you does not call super(..)
        // then java will call to default Constructor of the parent class.
        // super()
        
        this.weight = weight;
    }


    // Constructor with 2 parameters.
    public Mouse(String name, int weight) {
        super(name);
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String getAnimalName() {
        return "Mouse";
    }
}
  • InstanceofDemo.java
package org.o7planning.tutorial.inheritance.demo;

import org.o7planning.tutorial.inheritance.animal.Animal;
import org.o7planning.tutorial.inheritance.animal.Cat;
import org.o7planning.tutorial.inheritance.animal.Mouse;

public class InstanceofDemo {

    public static void main(String[] args) {

        
        // Create an Animal object.
        // Animal is abstract class
        // It can not create the object from its constructors.
        Animal tom = new Cat("Tom", 3, 20);

        System.out.println("name: " + tom.getName());
        System.out.println("animalName: " + tom.getAnimalName());


        // Using instanceof operator to
        // check if an object is an instance of a specific class.
        boolean isMouse = tom instanceof Mouse;
        System.out.println("Tom is mouse? " + isMouse);

        boolean isCat = tom instanceof Cat;
        System.out.println("Tom is cat? " + isCat);

        boolean isAnimal = tom instanceof Animal;
        System.out.println("Tom is animal? " + isAnimal);

    }

}
Results of running the example:
  • InheritMethodDemo.java
package org.o7planning.tutorial.inheritance.demo;

import org.o7planning.tutorial.inheritance.animal.Cat;

public class InheritMethodDemo {

    public static void main(String[] args) {

        // Create instance of Cat.
        Cat tom = new Cat("Tom", 3, 20);
        
        
        // Call the method inherited from the parent class.
        System.out.println("name: " + tom.getName());
        System.out.println("animalName: " + tom.getAnimalName());
        
        System.out.println("-----------------");

        // Call the method declared in the class Cat.
        System.out.println("Age: " + tom.getAge());
        System.out.println("Height: " + tom.getHeight());
    }

}
Results of running the example:

Casting in Java

  • CastDemo.java
package org.o7planning.tutorial.inheritance.demo;

import java.util.Random;

import org.o7planning.tutorial.inheritance.animal.Animal;
import org.o7planning.tutorial.inheritance.animal.Cat;
import org.o7planning.tutorial.inheritance.animal.Mouse;

public class CastDemo {

    // Method returns a random animal.
    public static Animal getRandomAnimal() {
        // Returns a random value 0 or 1
        int random = new Random().nextInt(2);

        Animal animal = null;
        if (random == 0) {
            animal = new Cat("Tom", 3, 20);
        } else {
            animal = new Mouse("Jerry", 5);
        }
        return animal;
    }

    public static void main(String[] args) {

        Animal animal = getRandomAnimal();

        if (animal instanceof Cat) {
            // Cast to Cat
            Cat cat = (Cat) animal;

            // And call method of the Cat class.
            System.out.println("Cat height: " + cat.getHeight());
        } else if (animal instanceof Mouse) {
            // Cast to Mouse
            Mouse mouse = (Mouse) animal;

            // And call method of the Mouse class.
            System.out.println("Mouse weight: " + mouse.getWeight());
        }

    }

}

4- Polymorphism in Java

You have a cat Asian Cat, you can call it is a Cat or call it is an Animal which is an aspect of the polymorphism.

Or another example: On your resume records that you're an Asian man, while you actually are a Vietnamese.

The example below shows you how to behave between declaring and reality
AsianCat is a subclass of the class Cat.
  • AsianCat.java
package org.o7planning.tutorial.inheritance.animal;

public class AsianCat extends Cat {

    public AsianCat(String name, int age, int height) {
        super(name, age, height);
    }

    // Override methods of the parent class (Cat)
    @Override
    public String getAnimalName() {
        return "Asian Cat";
    }
}
Polymorphism of Java is described in the following illustration:
  • PolymorphismDemo.java
package org.o7planning.tutorial.polymorphism;

import org.o7planning.tutorial.inheritance.animal.AsianCat;
import org.o7planning.tutorial.inheritance.animal.Cat;

public class PolymorphismDemo {

   public static void main(String[] args) {

       Cat cat1 = new Cat("Tom", 3, 20);

       Cat cat2 = new AsianCat("ATom", 2, 19);

       System.out.println("Animal Name of cat1: " + cat1.getAnimalName());

       System.out.println("Animal Name of cat2: " + cat2.getAnimalName());

   }

}
Results of running the example: