I had a question about inheritance on a Java exam. It went like this:
class A{
public int getInt(){
return 0;
}
}
class B extends A{
public int getInt(){
return 60;
}
}
class C extends B{
public int getInt(){
return 150;
}
}
class Z4{
public static void main(String[] args){
A c1 = new C();
B c2 = new C();
C c3 = new C();
System.out.println(c1.getInt() + " " + c2.getInt() + " " + c3.getInt());
}
}
The code prints out "150 150 150"
I understand why it does that: the variables are the type expressed on the left side of the operator, but the objects are the type expressed on the right side of the operator. Since all objects are type C, they all use C's overridden method.
Furthermore, if class C had an overloaded (as opposed to overridden) method, the first two variables would not have been able to use it, since they variable types don't have that method signature.
On a side note, a variable of type superclass can reference an object of type subclass. But a variable of type subclass can't reference an object of type superclass. "Super myObject = new Sub();" works. "Sub myObject = new Super();" doesn't.
My first question is: Are the above statements correct? My second question is: when would you do that?
In my very limited experience, I've made ArrayLists of type superclass and populated it with objects of various subclasses. I see where that comes in handy. But is there a case where you specifically create variables that are a different type from their object? Do you ever enter "SuperClass myObject = new SubClass();"? I can't see a practical use for that.