Subclasses

  • Method to create hierarchy between classes by inheriting from other classes
  • parent and child classes
  • extends extend a class to show its inherited and extends functionality
  • Subclass inherits all methods and fields from superclass, and constructor can be carried out from subclass
  • super refers to superclass or parent objects
// Hacks 1
private class Plane {
    private String model = "Boeing 737";
    private int age = 3; //two attributes

    public void getAge(String model, int age) {
        println("Age: " + age);
    }
}

private class Jet extends Plane {
    private String color = "blue";
    
}

Overload & Override

  • Overload happens when there are two methods with same name but different arguments or parameters
  • Method override happens when child class has the same method that is present in a parent class, overwrites base class method
//hack 2
public class Plane {
    private String model = "Boeing 737";
    private int age = 3;

    public void engineBurr() {
        System.out.println("brrrrrr");
    }
}

private class Jettison extends Plane {
    public Jettison(String model, int age, String color) {
        super(model, age); 
        this.color = color; 

        @Override
        public void engineBurr() {
        System.out.println("BRRRRRRRRR"); 
    }

}

Polymorphism

  • Ability of class to provide different implementations of methods, such as overloading, overriding, late binding
//Hack 3
private class Jets extends Plane {
    @Override
    public void getAge(String model, int age, String color) {
        println("Age: " + age);
    }

    public void getAge(int age, String color) {
        println("Age: " + age);
    }
}