Reputation: 10610
Please forgive me if this question is silly as i'm completely new to JAVA program. I'm looking into nested classes concept and come across the following program.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("Display: outer_x = " + outer_x);
}
}
}
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
// Inner inner = new Outer().Inner();
// inner.display();
}
}
And my doubt is how to access members of Inner
class from NestedClass
. In "Java - The complete reference", it is given that "You can, however, create an instance of Inner outside of
Outer by qualifying its name with Outer, as in Outer.Inner"
. But if i try to use it as,
Inner inner = new Outer().Inner();
inner.display();
it is throwing error. So please help me experts.
Upvotes: 2
Views: 92
Reputation: 1190
Outer st = new Outer();
Outer.Inner fl = st.new Inner();
Note that the code above would be exactly the same whether the main()
method is inside the outer class
(because main is a static method) or even in some other class. Some other class could only run the code if it has access to outer class . But, Outer Class will have default, or package access since access modifiers are not specified when Outer Class is declared. This essentially means that any class within the same package as OuterClass will be able to run the code above without any issues.
Upvotes: 3
Reputation: 8975
Use this:
Outer.Inner inner=new Outer().new Inner();
as you need to create object of Inner class too as it is not static inner class.
So your code becomes:
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
Upvotes: 1
Reputation: 45060
You need to create a new Inner
instance by using the new
keyword.
Inner inner = new Outer().new Inner(); // "new" keyword is required to create a new Inner instance.
If you do not have the import for import com.java.test.Outer.Inner;
added, add it. Or else, you can do something like this
Outer.Inner inner = new Outer().new Inner();
Upvotes: 5
Reputation: 3414
Inner class
can be accessed only through live instance of outer class
.
Try this:
class NestedClass {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
Upvotes: 1
Reputation: 929
You first have to create an instance of the outer class. After that, you can create an instance of that nested inner class by the outer class' instance.
Outer outer = new Outer();
Outer.Inner a = outer. new Inner();
a.display();
Upvotes: 2