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

2
  • 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? Commented Dec 27, 2020 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. Commented Dec 27, 2020 at 15:25

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot it worked. Also cleared up things.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.