Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using superclass to initialise the subclass object and vice versa?

Tags:

java

oop

Can you please tell me difference between these three in respect to their usage :-

Superclass p1 = new Superclass();
Superclass p2 = new Subclass();
Subclass p3 = new Subclass();
like image 971
pranavj95 Avatar asked May 13 '15 20:05

pranavj95


2 Answers

The first one and the 3rd one make respective objects of the type declared - usage is perfect, and you get all the expected methods.

The second one gives you the functionality of only the Superclass even though you actually have a Subclass object, because you declared it as a Superclass.

eg:

Superclass p1 = new Superclass(); Your p1 object has access to Superclass methods.

Superclass p2 = new Subclass(); Your p2 object only has access to Superclass methods. The program doesn't know p2 has Subclass specific methods because you declared it as a Superclass.

Subclass p3 = new Subclass(); Your p3 object has access to all Subclass and Superclass methods.

Note for using p2 method of declaration: Given the following classes A and B

public class A {
    public void print(){
        System.out.println("yyy");
    }
}

public class B extends A{
    public B() {
        super();
    }

    public void print() { // this overrides the print() method in A
        System.out.println("xxx");
    }

    public void printb() {
        System.out.println("second");
    }
}

This happens in code:

public static void main(String[] args) {
    A x =  new B();

    x.print(); // prints xxx because you actually have a B object even though you have an A reference
    x.printB(); // doesn't compile. You can't call B specific methods through an A reference.
}
like image 56
Aify Avatar answered Oct 15 '22 11:10

Aify


The first and the last are just usual variable declaration and class instantiation.

The second

Superclass p2 = new Subclass();

declares a variable p2 of type Superclass that can either store a Superclass instance or any instance of a subclass of Superclass. From p2 you can only access members that are already provided in Superclass, although their behavior can be different due to overriding in Subclass.

Also, you can check what actual type is stored in p2 by using instanceof. If you know the actual type, you could cast p2 to another variable of the sub-class type.

if (p2 instanceof Subclass)
    Subclass p4 = (Subclass)p2;
like image 29
adjan Avatar answered Oct 15 '22 09:10

adjan