Recently my teacher was talking about using different constructors to instantiate objects. But I'm really confused about that. For that I wanna understand why the I get the following compile error.
class SuperClass {
void superClass(){
System.out.println("superClass");
}
}
class SubClass extends SuperClass {
void subClass(){
System.out.println("subClass");
}
}
class Call {
public static void main(String args[]){
SuperClass s = new SubClass();
s.superClass();
}
}
When I compile and run the following code, I get the output
superClass
But when I try to call subClass()
via the s
Object, I get the following error.
damn.java:17: cannot find symbol
symbol : method subClass()
location: class SuperClass
s.subClass();
^
1 error
OK so, according to this, I can assume that the even I instantiate object with a different constructor, only the Object type specified is loaded to the RAM.
But, when I use the override here like this,
class SuperClass {
void superClass(){
System.out.println("superClass");
}
}
class SubClass extends SuperClass {
void superClass(){
System.out.println("subClass");
}
}
class Call {
public static void main(String args[]){
SuperClass s = new SubClass();
s.superClass();
}
}
I get the method in the sub class called. Which makes me really confused about this. Anyone can please explain me what happens here when I use a different constructor to instantiate an Object.