Search code examples
javaobjectinheritance

Why is the compiler not throwing error when Assigning object of sub class to parent reference


class Base {
    public void show() {
        System.out.println("Base class show() method called");
    }
}

class Derived extends Base {
    public void show() {
        System.out.println("Derived class show () method called");
    }
}

public class Main {
public static void main(String[] args) {
    Base b = new Derived();//why is java allowing me to create an object of child class
    b.show();              //how can the Base class hold and use the reference of child
    }                              
}

What if I create an new method in the child class ?? Will the parent class still be able to access the new method ??

class Derived extends Base {
    public void show() {
        System.out.println("Derived class show () method called");
    }
    public void poo() {
        System.out.println("take a poo");
    }
}

public class Main {
public static void main(String[] args) {
    Base b = new Derived();
    b.show();   
        b.poo(); 
    }                              
}

Why is java allowing me to assign a reference of child to base class and not throwing any warnings or errors.


Solution

  • This is called polymorphism. Any derived class can necessarily be considered an instance of a parent class (without explicit casting).

    The methods you can call and fields you can access depend on the static type of the object. In the case of Base b = new Derived();, the static type of b is Base, so you can only call methods visible on Base. New methods defined in Derived cannot be used.