I would like to understand why is it happening like that and what is the use of the advantage following phenomenon: I use Superclass to initialize a subclass object, why will the object have the attributes of the subclass and but the methods of the superclass?
See the code to understand what I really mean:
class SuperClass {
public String s = "'This is the superclass'";
public String method() {
return s;
}
}
class SubClass extends SuperClass {
public String s = "'This is the subclass'";
public String method() {
return s;
}
}
public class SubClassTest {
public static void main(String[] args) {
SuperClass sc = new SuperClass();
System.out.println("Superclass s: " + sc.s + " bzw. method: " + sc.method());
SubClass subc = new SubClass();
System.out.println("SubClass s: " + subc.s + " bzw. method: " + subc.method());
SuperClass x = subc;
System.out.println("x s: " + x.s + " bzw. method: " + x.method());
}
}
The output is the following:
Superclass s: 'This is the superclass' bzw. method: 'This is the superclass'
SubClass s: 'This is the subclass' bzw. method: 'This is the subclass'
x s: 'This is the superclass' bzw. method: 'This is the subclass'