How to define a constructor of a subclass inheriting an inner class?

I am learning inner and outer classes in Java. I know what internal and external classes are and why they are used. I came across the following question on this topic and could not find an answer.

Suppose the following code is given:

class outer{
    class inner{

    }
}

class SubClass extends outer.inner{
}

Question: How to define a minimal constructor for a subclass? and why?

Option 1-
Subclass () {
    //reason: bacause the default constructor must always be provided
}
Option 2-
Subclass (Outer outer) {
    //reason : because creating an instance of **Subclass** requires an instance 
    //of outer, which the **Subclass** instance will be bound to
}

Option 3-
Subclass (Outer outer) {
    outer.super();
    //reason : because creating an instance of **Subclass** requires an explicit 
    //call to the **Outer's** constructor, in order to have an enclosing instance 
    //of **Outer** in scope.
}
Option 4- 
Subclass (Outer.inner inner) {
    //reason : bacause an instance of **inner** is necessary so that there is a 
    //source to copy the derived properties from
}

PS. This is a multiple choice question. Only 1 answer expected

I am new to java and know little about these advanced topics

thank

+4
source share
2 answers

JLS, , , :

8.8.7.1-1.

class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner() { (new Outer()).super(); }
}

:

  • super (, ).

  • .

, (Β§8.1.3). , .

, ,

public SubClass(Outer outer) {
    outer.super();
}

Outer.Inner, Outer, SubClass Outer, .

outer.super(); Outer, Inner.

outer.super(); , super() , , , .

+2

, "" . , .

, .

, , :

class Outer {
   class Inner {
      ...
   }
   class SubInner {
      ...
   }
   void method() {
      Inner i = this.new SubInner();
   }
}
0

Source: https://habr.com/ru/post/1681695/


All Articles