Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner/Outer class obj.new

Tags:

java

This is the example of member inner class that is invoked outside a class.

//Program of memeber inner class that is invoked outside a class

class Outer {
    private int data=10;

    class Inner {
        void msg() {
            System.out.println("Data: " + data);
        }
    }
}

class Test {
    public static void main(String args[]) {
          Outer obj=new Outer();
          Outer.Inner in = obj.new Inner();
          in.msg();
    }
}

Could someone explane this line of code: Outer.Inner in = obj.new Iner(); what does obj.new Inner() mean?

like image 522
user16401 Avatar asked Apr 17 '26 14:04

user16401


2 Answers

It's important to understand that Outer and Inner are related. More specifically, you need an Outer instance in order to create an Inner instance.

Outer.Inner in = obj.new Inner();

creates an Inner instance from obj, an Outer instance. You can see that these two are related in that the msg() method of in will use obj's data field: in makes use of obj's state. If Inner was static it wouldn't have any relationship with Outer, so you could just use

Outer.Inner in = new Outer.Inner();  // no Outer instance needed

Of course in your case you can't simply make Inner static because it uses the data field.

like image 139
arshajii Avatar answered Apr 20 '26 06:04

arshajii


Outer.Inner in = obj.new Iner();

Using reference of outer object you are creating object for Iner class, because Iner is part of Outer class. Here is more information.

like image 38
kosa Avatar answered Apr 20 '26 06:04

kosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!