سؤال

I have a class say A, and a static nested class say B.

public class A {
    public static class B {
        B(Temp x) {
            x.reg(this); // need to pass the nested class reference.
        }
    }
}

Is the above code correct? Can we use this keyword inside nested static class constructor?

Please help me on this. Thanks.

هل كانت مفيدة؟

المحلول

yes, it is. For the runtime, inner classes are just another, separate class. If the inner class is not static it will just have a reference to the outer class, but in your case it's static so not even, so it is exactly as if you created a new class in a new file

Just make sure that you write "public", not "Public"

نصائح أخرى

1) Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.

2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.

3) An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don’t need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.

for More information please refer this http://www.geeksforgeeks.org/static-class-in-java/

The behavior of the static class in just like a static method. This class belongs to the class but not the instance. Hence, this has no meaning in the static context.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top