[JAVA] Let me ask you a question about using nested class object declarations in static member methods.

Asked 2 years ago, Updated 2 years ago, 69 views

Let me ask you a question about the use of nested classes in the static member method of the class.!

public class A {
    public static void methodA() {
        BB = new B(); // Error
    }

    class B {
        // // empty
    }
}

Like the code above, within the class A, The static member method A exists and within class A, In situations where class B, which is an overlapping class, exists, I want to create class B and use it, but there is an error. I don't understand why there is an error.

The development tool kindly told me to make B class static.

I'm not sure why it should be static.

I know this code is possible.

public class A {
    public static void methodA() {
        B b = new B(); 
    }
}
class B {
        // // empty
}

In the case of this code, the book says that if you want to use an instance member in a static block, you have to create an object first and then approach it as a reference variable.

But I don't really understand the first code.

Since methodA() is declared static, it should be accessible without object creation.

So in the first code, like the second code, it creates an object in a static method to approach it.

Why does this have an error?

public class A {
    public static void methodA() {
        BB = new B(); // Error
    }

    static class B {
        // // empty
    }
}

I said it at firstIf you change it to static in class B, it will be solved.

Why do you get an error if you use the first code like the second code?

Instant access is not available in static method

Is it because the overlapping class is also an instance judgment?

java inner-classes

2022-09-20 19:28

1 Answers

It's a grammatical constraint of JAVA.

class A{
    class B{
        }
}

In principle, class B is a member of class A in Java.

If you declare something without any keywords inside the class, I understand that all Java sees it as a member of the class.

Therefore, JAVA does not allow access to members that are not even created, so it is considered an error.

If you add a static keyword. I don't know what JAVA uses. It is considered accessible because it is a class variable of class A.


2022-09-20 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.