How super implemented in Java?

Where is super defined? [When we use super.someMethod ()]. Is this a field in the java.lang.Object class or the java.lang.Class class?

When we call from a subclass, super contains a reference to the superclass. Similarly, the super in the superclass has a link to the superclass [Thus, prior to java.lang.Object]. So, how does java enter superclass references in the "super" field, which allows us to call superclass methods?

Are there any options for implementing the hood, such as:

Class current = this.getClass(); Class parent = current.getSuperclass(); System.out.println("name is =" + parent); 
+8
java inheritance super jvm superclass
source share
5 answers

super is the keyword of the reference object that goes up to the hierarchy of objects, starting with the calling object, until it finds an ancestor object that has the signature of the matching method or property / field. Refer to the Java documentation .

+2
source share

super like this is a keyword. It has a value in Java that is not reflected in Java bytecode. This means implementing my parent classes (which can be inherited)

At the byte code level, it will invoke the method for its parent class explicitly.

+15
source share

This is not a field - it is a language keyword .

There is a link to the superclass at the JVM level, of course, but at the Java level you can access it only through the keyword. The difference is that you could not actually access the superclass method via a link - this requires special support from the compiler. And of course there is no super.super

+2
source share

Is it defined as a field in the java.lang.Object or java.lang.Class class?

This is not a field at all.

super.someMethod() is a Java syntax element that says: "Call the method defined in my superclass."


OK, suppose this was a field. What would be his type? What will it refer to? If it was declared as:

 Class<ParentClass> super = ... // the relevant class object. 

then super.someMethod() will not work because:

  • Class has no user methods and
  • super.someMethod() must be an instance method call, and we do not supply a suitable instance.

On the other hand, if it was declared as:

 ParentClass super = this; 

then super.someMethod() will be equivalent to this.someMethod() and will call a method in this class, not overridden.

+1
source share

I assume that he will begin to climb the chain of ancestors until he finds the first class that has a method that you put on super. This is the easiest way. This is done at compile time if you think about it. In the end, a method is just a pointer to a function, with an invokation method that takes a given instance (in this case, this ). See Document Method.invoke

It will be used by the compiler with an instance of Method from the superclass, and this is like an instance of an object

0
source share

All Articles