user8608687
user8608687

Reputation: 1

How to make a subclass accessible from instance only?

I'd like to create a subclass accessible only from an instance of the superclass, but not from the superclass itself, to be sure that the superclass' variables have been initialized. For example:

public class SuperClass 
{
     int num;
     
     SuperClass(int number){
         num = number;
     }
     //Make this\/ accessible from instance only
     class SubClass
     {
         SubClass(){}

         public int read(){
             return num;
         }
     }
}

In another file:

public void err(){
    SuperClass.SubClass obj = new SuperClass.SubClass(); //Error! Superclass is not an instance
    System.out.println(obj.read());
}
public void right(){
    SuperClass sup = new SuperClass(3);
    SuperClass.SubClass obj = new sup.SubClass(); //Correct, sup is an instance
    System.out.println(obj.read()) //Print 3

Upvotes: 0

Views: 205

Answers (2)

vincendep
vincendep

Reputation: 607

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass { ... class InnerClass { ... } }

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); There are two special kinds of inner classes: local classes and anonymous classes.

check the link

Upvotes: 0

Justin
Justin

Reputation: 415

That's not possible. Non-static inner classes have to be instantiated through an instance of an outer class. See this link for more info.

Upvotes: 1

Related Questions