Home  >  Article  >  Java  >  What is inheritance of inner classes in java

What is inheritance of inner classes in java

coldplay.xixi
coldplay.xixiOriginal
2020-09-02 14:10:222668browse

Inheritance of java internal classes: Because when the exported class is instantiated, there is no peripheral class object for the instance of the exported class to connect to it. So we need to create an outer class and use a specific syntax to indicate the relationship between the inner class and the outer class.

What is inheritance of inner classes in java

Inheritance of java inner classes:

The constructor of a Java inner class must be connected to a pointer to its enclosing class object reference (to construct an inner class, you must give it a reference to the 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 derived class .

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

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

In the following example, you need to give the derived class InheritInner a reference from the outer class of the inner class. For ordinary inheritance, you only need to add super(); to the exported class constructor, while inner classes need to reference the outer class object .super();

class WithInner{
  class Inner{}
 }
 public class InheritInner extends WithInner.Inner{
  InheritInner(WithInner wi){
     wi.super(); //wi的父类是object
   }
   public static void main(String[] args){
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
  }
 }

Moreover, what should we do when the inherited inner class only has a non-default constructor?

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);//如代码所示,当被继承的构造器需要参数时,应把参数传递给这个super函数
  }
  public static void main(String[] args){
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
  }
}

Related learning recommendations: java basic tutorial

The above is the detailed content of What is inheritance of inner classes in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn