I really don't understand why the getMyClass2 method below cannot be static, why isn't it valid Java code?
public class MyClass
{
private class MyClass2
{
public String s1 = "";
public String s2 = "";
}
private MyClass2 myClass2;
private static MyClass2 getMyClass2()
{
MyClass2 myClass2 = new MyClass2();
return myClass2;
}
public MyClass()
{
myClass2 = getMyClass2();
}
}
Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes. An instance of an inner class cannot be created without an instance of the outer class.
it is a static method (static), it does not return any result (return type is void), and. it has a parameter of type array of strings (see Unit 7).
Java static nested classA static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.
They are accessed using the enclosing class name. For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass.
You have to say that the inner class is static because non-static is bound to the instance so it cannot be returned from static method
public class MyClass
{
private static class MyClass2
{
public String s1 = "";
public String s2 = "";
}
private MyClass2 myClass2;
private static MyClass2 getMyClass2()
{
MyClass2 myClass2 = new MyClass2();
return myClass2;
}
public MyClass()
{
myClass2 = getMyClass2();
}
}
The (non static) inner class instances are always associated with an instance of the class they are contained within. The static method will be called without reference to a specific instance of MyClass, therefore if it created an instance of MyClass2 there would be no instance of MyClass for it to be associated to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With