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
What does super
present? Is it object of parent class, which child keeps as field?
I tried to Google, but all I found is common information about how to inherit classes and so on.
You are still telling me obvious things. Maybe my question was little misleading, but I'll try to rephrase it:
super
, you say, we are accessing parent's method. But how can we call this method without parent's object?super
same as this
? this
is a reference to concrete object, as you know.Inheritance is one of the core concepts of object-oriented programming (OOP) languages. It is a mechanism where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods.
Types of Inheritance in Java: Single, Multiple, Multilevel & Hybrid.
Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.
Inheritance in java is a core concept that requires the properties of one class to another class like a guardian. For example the relationship between father and son. Or also we can say that the properties derived from one class to another class are a term inheritance.
The child class does not maintain any special field representing its parent. You may be thinking something along the lines of inner classes, which do maintain a reference to their outer class. This is a special case and does not represent how super-sub classes relate to each other.
Internally, the JVM maintains a 'method table', associating each class its loaded with the methods available for that class. The JVM also knows about the relationships between all classes its loaded, including super-sub relationships.
When you invoke a super
function, the JVM actually does a couple of things:
invokespecial
)If you were to examine the class file for your Sub
class, you would see something like this for the foo
method:
void foo();
flags:
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #2 // Method Super.foo:()V
4: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
7: ldc #4 // String Sub
9: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
Line 1 in the listing shows the special instruction that invokes the superclass method.
A good source of reading would be the Java Virtual Machine Specification, particularly Section 2.11.8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With