We have next classes:
class Super {
void foo() {
System.out.println("Super");
}
}
class Sub extends Super {
void foo() {
super.foo();
System.out.println("Sub");
}
}
public class Clazz {
public static void main(String[] args) {
new Sub().foo();
}
}
Output is:
Super
Sub
Questions:
What does super present? Is it object of parent class, which child keeps as field?
- If it is, how does inheritance of abstract classes work? You can not create instance of abstract class.
- If it is not, where are overridden method hold?
I tried to Google, but all I found is common information about how to inherit classes and so on.
Update:
You are still telling me obvious things. Maybe my question was little misleading, but I'll try to rephrase it:
- When we are calling method with
super, you say, we are accessing parent's method. But how can we call this method without parent's object? - Is
supersame asthis?thisis a reference to concrete object, as you know.
super.someMethodyou instruct the JVM to resolve the symbolic reference for the method from the parent class, as opposed to the class in context.Superbecause you already have an instance ofSub, which knows the implementation of all the methods that theSuperclass has, has all of its fields, etc. When you call the superclass method withsuper.foo()it's called on the instance of the subclass, but it uses the implementation defined in the superclass, not the subclass.