Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a non-static inner class in Java?

The reason I need the inner class to be non static is because I need the the inner class to have access to to a generic of the class which it is inside.

Thanks in advance.

like image 339
rustybeanstalk Avatar asked Mar 27 '12 01:03

rustybeanstalk


People also ask

Can you extend a static inner class in Java?

Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. You can extend static inner class with another inner class.

Can inner class non-static?

Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.

Which class Cannot extend?

A final class cannot extended to create a subclass. All methods in a final class are implicitly final . Class String is an example of a final class.

Should all inner classes be static?

Inner classes which do not reference their owning classes should be "static" A non-static inner class has a reference to its outer class, and access to the outer class' fields and methods. That class reference makes the inner class larger and could cause the outer class instance to live in memory longer than necessary.


2 Answers

I speculate that you want to extends a non-static inner class from outside an enclosing instance, which is possible.

class Alpha
{
      class Beta ( ) { }
}

class Gamma extends Alpha . Beta
{
      // important to get the constructor right or else the whole thing fails
      Gamma ( Alpha alpha )
      {
             alpha . super ( ) ;
      }
}

You can also extend the inner class inside the original enclosing class

class OuterParent
{
     class InnerParent { }

     class InnerChild1 extends OuterParent { }
}

or extend the original enclosing class and extend the inner class in the child class

class OuterChild extends OuterParent
{
     class InnerChild2 extends OuterParent { }
}
like image 128
emory Avatar answered Oct 13 '22 10:10

emory


Yes, it is possible. It will have access to the members of the enclosing class.

like image 20
trutheality Avatar answered Oct 13 '22 10:10

trutheality