I feel I have a decent understanding of inheritance in Java but am struggling with the following situation:
public class SuperClass {
private String name;
private int age;
public SuperClass(String name, int age) {
this.name = name;
this.age = age;
}
public void sharedMethod() {
System.out.println("I'm a shared method in the SuperClass");
}
}
public class SubClass extends SuperClass {
public SubClass(String name, int age) {
super(name, age);
}
public void sharedMethod() {
System.out.println("I'm a shared method in the SubClass");
}
public void subMethod() {
System.out.println("I'm subMethod");
}
}
public class Main {
public static void main(String args[]) {
SuperClass test = new SubClass("Laura", 30);
test.sharedMethod();
test.subMethod(); // causes an error
}
}
I am primarily struggling to understand what is actually being created here when using SuperClass test = new SubClass("Laura", 30);
(which only seems to work when SubClass
extends SuperClass
- how's that possible without Casting?).
The reason I don't understand it is because I can call the sharedMethod
which prints out the text from the SubClass
method (so presumably SubClass
is overriding the SuperClass
method in this instance), but yet I can't call the subMethod
from the SubClass
at all. Sorry if I didn't articulate it very well, I just can't seem to wrap my head around what is being referenced, what methods can be used, why you would do this, why the SubClass
overrides a method if the method is shared, but can't be called otherwise.
By SuperClass test = new SubClass("Laura", 30)
, you create a SubClass
instance, but reference it by SuperClass
.
At compile stage, the compiler found that SuperClass
does not have method subMethod
, so you get compile error.
At runtime, JVM found that test
is actually a SubClass
, so the sharedMethod
from SubClass
:
public void sharedMethod() {
System.out.println("I'm a shared method in the SubClass");
}
will be executed.