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();
}
}
-
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– das-g2015-10-18 11:59:07 +00:00Commented Oct 18, 2015 at 11:59
-
Don't nest the Child4 class into the Base class. Use 2 different files: one for each class.JB Nizet– JB Nizet2015-10-18 12:14:19 +00:00Commented Oct 18, 2015 at 12:14
-
Possible duplicate of non-static variable cannot be referenced from a static contexttakendarkk– takendarkk2015-10-18 12:30:54 +00:00Commented Oct 18, 2015 at 12:30
Add a comment
|
2 Answers
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.