Reputation: 51
Why its saying
error No enclosing instance of type Demo is available due to some intermediate constructor invocation
class Demo {
class DemoInner{
DemoInner(){
System.out.println("DemmoInner");
}
}
}
public class Noding extends Demo.DemoInner{
Noding(){
super();
System.out.println("Noding");
}
public static void main(String[] args) {
new Noding();
}
}
Noding
is a child of Demo.DemoInner
and Demo.DemoInner
is an instance thing of Demo
class.
So while creating Child class Noding
instance, calling super
should not be giving a problem becasue parent should be in existence before creating child. And in this case parent is Demo.DemoInner
for Noding
and Demo.DemoInner
can't exist without Demo
.
So why its giving error while calling super()
in Noding
constructor ?
Upvotes: 1
Views: 56
Reputation: 1
Making DemoInner as a static class shall make the code run. DemoInner is a non-static inner class and hence it is associated with the instance of Demo class.
You can't call its constructor from Noding without making the class static.
class Demo {
static class DemoInner{
DemoInner(){
System.out.println("DemmoInner");
}
}
}
public class Noding extends Demo.DemoInner{
Noding(){
super();
System.out.println("Noding");
}
public static void main(String[] args) {
new Noding();
}
}
Upvotes: 0
Reputation: 12478
Unless it is declared as static
, it is dynamic, that is the object needs to be instantiated.
If you declared DemoInner like this:
class Demo {
class DemoInner{}
}
It means DemoInner class is one of the instances of Demo. So when you use DemoInner class, you need to instantiate Demo class first. And access DemoInner as the Demo instance's member object (see @AlexeyKonovalov's answer).
Or a workaround is to make DemoInner static (as @RobOhRob commented). Once declared static, it is no longer a member object of the outer class Demo object. You can access DemoInner class whether the outer class is instantiated or not.
class Demo {
static class DemoInner{}
}
Upvotes: 1
Reputation: 30
The call to the inner class is called like this:
class Noding extends Demo {
public static void main(String[] args) {
Demo demo = new Demo();
Demo.DemoInner inner = demo.new DemoInner();
System.out.println(inner);
}
}
Upvotes: 1