2

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();

  • 1
    Not without creating an `Outer` first. Since the `Inner` is not `static` it cannot exist without an `Outer`. You are mixing nested classes and polymorphism, are you sure you want to do that? – luk2302 Dec 27 '20 at 15:22
  • Actually yes. Since I am new to OOPs I was trying different combinations that can be possible to work together. Thanks a lot for your info tho. – Shubham Saurabh Dec 27 '20 at 15:25

2 Answers2

1

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();
Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74
0

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

user902383
  • 8,420
  • 8
  • 43
  • 63