chachay
chachay

Reputation: 340

java: extends a inner class

jdk version:1.8.0_241

There is a class extending a inner class. Code as follows:

class WithInner {
    class Inner {

    }
}

public class ExtendInnerClass extends WithInner.Inner {
    ExtendInnerClass(WithInner withInner) {
        withInner.super(); 
    }
}

To connect WithInner class's object and Inner class's object, we have to use super() method. But when i decompiled the class file, i find something interesting.

public class ExtendInnerClass extends Inner {
    ExtendInnerClass(WithInner withInner) {
        withInner.getClass();
        super(withInner);
    }
}

I find that compiler not only use super() method but also withInner.getClass().

why he do this?

Upvotes: 1

Views: 65

Answers (1)

chachay
chachay

Reputation: 340

An inner class object usually need to hold a reference to its outer class object.

Inner class has loaded before outer class without getClass(), it doesn't meet the principle of jvm, so use getclass() to load outer class in jvm before inner one.

Upvotes: 1

Related Questions