class Base {
Base show() {
System.out.println("Base");
return new Base();
}
class Child4 extends Base {
Child4 show() {
System.out.println("Child4");
return new Child4();
}
}
public static void main(String... s) {
Child4 C1 = new Child4();
C1.show();
}
}
Asked
Active
Viewed 1.3k times
2
-
Hi Disha. Welcome to stack overflow. Please make it easier to understand your question: What do you try with the code you posted? Do you get an error message, or does the code behave differently than you think it should? What do you think it should do, and what behavior did you observe? – das-g Oct 18 '15 at 11:59
-
Don't nest the Child4 class into the Base class. Use 2 different files: one for each class. – JB Nizet Oct 18 '15 at 12:14
-
Possible duplicate of [non-static variable cannot be referenced from a static context](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – takendarkk Oct 18 '15 at 12:30
2 Answers
2
In your sample, Child4
is a non static inner class of class Base
(see here for documentation on inner classes). This means you need an instance of class Base
in order to instantiate an object of class Child4
.
Since in you example there is no access from the Child4
instance to the outer Base
instance, it seems the use of a non static inner class is not intended. You should declare this inner class static, with
static class Child4 extends Base {
This way, the call to new Child4
will be legit from main
static context.

tonio
- 10,355
- 2
- 46
- 60
0
You can do this:
public static void main(String... s) { Base base= new Base(); Base.Child4 C1 = base.newChild4(); C1.show(); }

CHHIBI AMOR
- 1,186
- 2
- 13
- 27