Inheritance of Java inner classes (all)

  • 2020-04-01 04:02:30
  • OfStack

The following example code to share with you about the inheritance of JAVA inner class, the specific details are as follows:

The constructor of a Java inner class must be connected to a reference to its outer class object (the constructor of an inner class must give it a reference to an outer class object, and the inner class depends on the outer class object), so when inheriting the inner class, you need to manually add a call to the base class constructor in the constructor of the exported class.

Because, when the exported class is instantiated, there is no peripheral class object for the instance of the exported class to connect to.

So, we need to create a peripheral class and then use a specific syntax to indicate the relationship between the inner class and the peripheral class.

In the next example, you need to give the exported class a reference from the outer class of the inner class. For normal inheritance, you simply add super() to the exported class constructor. , while the inner class requires a reference to the outer class object.


class WithInner{
  class Inner{}
 }
 public class InheritInner extends WithInner.Inner{
  InheritInner(WithInner wi){
     wi.super(); //The parent of wi is object
   }
   public static void main(String[] args){
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
  }
 }

Further, what happens when the inherited inner class has only non-default constructors?


class WithInner{
  class Inner{
    public Inner(int i){
      System.out.println(i);
    }
  }
}
public class InheritInner extends WithInner.Inner{
  InheritInner(WithInner wi){
    int i=0;
    wi.super(i);//As the code shows, when an inherited constructor needs an argument, the argument should be passed to the super function
  }
  public static void main(String[] args){
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
  }
}    

The above is the inheritance of JAVA inner classes, I hope to help you.


Related articles: