Accessing nested class in another class of same package

Viewed 372

I am new to OOPs so sorry if it sounds very basic. I have a class with following code:-

    public class Outer {
    
    int x=90;
    class Inner extends Outer{  
         int x=150;  
        }  
}

Now suppose if I have another class 'Main' in the same package. Is there any way I can create an object of Class 'Inner' in 'Main' with reference of class 'Outer'?

I tried the following(it's throwing error):-

public class Main {

    public static void main(String[] args) {
        
        Outer O1 = new Inner();
        }

}

Both the classes 'Main' and 'Outer' are in same package. Also, my main objective is to know if there is any way create an object of class Inner in Main method like below:- Outer O1 = new Inner();

2 Answers

You need to create an object of outer first and then you can create an object of the inner class.

Outer o1 = new Outer().new Inner();

Inner classes (if they are not static) they require instance of outer class that it is bound to.

Related