0
public class InnerTest {

    public static void main(String arg[]) {
        A.B.print();
    }
}

class A {
    static class B {
        static void print() {
            System.out.println("Hello");
        }
    }
}

How can i call static class B using class name A although class A is not static

4 Answers4

3

This is not related to the class to be static or not, it is related the static keyword in the method.

take a look about How static keyword exactly works in Java? also read this article Java – Static Class, Block, Methods and Variables

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

One more aspect how to explain this:

class itself is not static or non static it is just a class.

You anyway can use static keyword only with class members. If you would try to declare InnerTest as static you would have an error that might look like this (so assuming it is not static nested class to some other class)

Illegal modifier for the class InnerTest; only public, abstract & final are permitted

static nested class can be used as in question because it does not require access to any instance member of InnerTest. In other words it can access static members and only those.

If it needs access to non static members then it can not be static and the way to call would be like new InnerTest().new B().

pirho
  • 11,565
  • 12
  • 43
  • 70
0

The static keyword is used to modify a member of a class. When a member is modified with static, it can be accessed directly using the enclosing class' name, instead of using an instance of the enclosing class like you would with a non-static member.

The inner class Inner below is a member of the class Outer:

class Outer {
    static class Inner {}
}

Therefore, Inner can be accessed like this:

Outer.Inner

Outer don't need to/cannot be modified by static because it is not a member of a class. It is a class existing in the global scope. To access it, you just write its name - Outer. It does not make sense for it to be non-static because it has no enclosing class. If it were non-static, how are you supposed to access it?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

To use the correct terminology, class B is not an inner class; it is a static nested class. See https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html for the definitions of the various types of nested class.

The important keyword is the static keyword in front of the definition of class B. It does not matter whether class A is static or not. In fact, it wouldn't make sense to put static in front of class A's definition.

Because class B is declared static, it doesn't keep a reference to an instance of class A.

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42