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();
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.
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With