How super is implemented in Java?

2019-06-16 19:26发布

问题:

Where the "super" is actually defined? [When we're using super.someMethod()]. Is it defined as a field in java.lang.Object class or java.lang.Class class?

When we're calling from a subclass, super contains the reference to it's superclass.In the same manner the super in superclass itself has reference to it's superclass [In this way upto java.lang.Object]. So, how java injects the superclass references to the "super" field which enables us to call superclass methods ?

Is there any under the hood implementaations like the following:

    Class current = this.getClass();
    Class parent = current.getSuperclass();
    System.out.println("name is =" + parent);

回答1:

super is an object-reference specific keyword that ascends the object hierarchy beginning from the calling object until it finds an ancestor object that has a matching method signature or property/field. Refer to Java documentation.



回答2:

super like this is a keyword. It has a meaning in Java which is not reflected in the Java byte code. It means my parent classes' implementation (which could be inherited)

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



回答3:

It's not a field - it's a language keyword.

There is a reference to the superclass at the JVM level, of course, but on the Java level you can only access it through the keyword. The difference is that you could not in fact access a superclass method through a reference - it takes special support from the compiler to do that. And of course there is no super.super



回答4:

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

It is not a field at all.

super.someMethod() is a Java syntactic element that says "call the method as defined in my superclass".


OK, suppose that hypothetically it was a field. What would its type be? What would it refer to? If it was declared as:

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

then super.someMethod() wouldn't work because:

  • Class doesn't have any user-defined methods, and
  • super.someMethod() needs to be a call to an instance method, and we are not supplying a suitable instance.

On the other hand if it was declared as:

ParentClass super = this;

then super.someMethod() would be equivalent to this.someMethod() and would call the method in this class, not the overridden on.



回答5:

I guess it will start climbing the ancestors chain until it finds the first class that has the method you put following super. Seems the easiest way. This is done at compile time if you think about it. In the end a method is just a function pointer, with an invokation method that accepts the instance in question (in your case it is this). Look the Method.invoke documentation

It will be used by the compiler with a Method instance from the super class and this as the Object instance