0
public class A{
      public static class B{
             public class B1 extends B{
             //it contains a constructor and some methods
             }
       }
         public static void main(...){
       //create B1 object here
       }
}

It works fine when I split the classes, but I need them in one java file. How would I create a B1 object in the main of class A?

  • Does this answer your question? [Java inner class and static nested class](https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class) – luk2302 Dec 30 '20 at 12:25
  • The `extends` is irrelevant, the relevant part is the nesting and which `class` is `static` or not. – luk2302 Dec 30 '20 at 12:26

2 Answers2

0

public class B1 extends B{

This is a mistake.

inner classes have a secret, invisible field, of the type of their parent. So, your B1 class both extends B, and has a field of type B that has no name but is there anyway (and you need it to make any instance of B1). That cannot be right.

What you probably want, is:

public static class B1 extends B { ... }

Once it is static, you can simply write: new B1();, or if you haven't imported B1 directly, new A.B.B1();. Without it, you can only write new A.B.B1() in a context where there is some this reference that would refer to an instance of B: Such as in any non-static method of B. Outside of such contexts, you'd have to write e.g.:

A.B b = new A.B();
b.new A.B.B1();

in order to 'set' that hidden field (it will point to the same object the b variable is pointing at here). But... you don't want this. Now your B1 instance both is a B and holds a B, and that would be very confusing. Just make B1 'static'. In fact, make all inner classes static unless you both [A] are really really sure you need an instance inner, and [B] you fully understand how that works.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

to access non static inner class create object of outer class and access inner class using that object as below:

B b = new B();
B.B1 obj= b.new B1();

visit this Java Inner Class (Nested Class) link here and practice.