Reputation: 53
I Have this class:
public abstract class Test {
public abstract class SubClass extends Test
{
}
}
I need to access it like this
public class JavaApplication1 extends Test.SubClass {
public JavaApplication1()
{
super();
}
}
But having problem with super. I Cant use it static nor extend Test What should I do? Thanks in advance
Upvotes: 2
Views: 174
Reputation: 213223
The problem is accessing an inner class needs an instance of the outer class. So, you can't directly invoke super()
from your JavaApplication1
constructor. The closest you can get is by creating a 1-arg constructor, passing the instance of the outer class, and then invoke super
on that instance: -
public JavaApplication1(Test test)
{
test.super();
}
And then invoke the constructor as: -
new JavaApplication1(new Test() {});
This will work fine. But, with 0-arg constructor, you would have to create an instance of Test
class first (in this case, an anonymous inner class, since Test is abstract), and then invoke super()
.
public JavaApplication1() {
new Test() {}.super();
}
Upvotes: 2
Reputation: 7440
Why are you extending an inner class from the outside of the class containing it? Inner class should be used only when you need a specific need inside a Class. If there are more classes that could benefit from the services offered by a Class then it shouldn't be inner but a top level class.
Upvotes: 2
Reputation: 285401
One solution: make SubClass a static inner class.
Another possible solution:
public class JavaApplication1 extends Test.SubClass {
public JavaApplication1() {
new Test() {}.super();
}
public static void main(String[] args) {
new JavaApplication1();
}
}
abstract class Test {
public Test() {
System.out.println("from Test");
}
public abstract class SubClass extends Test {
public SubClass() {
System.out.println("from SubClass");
}
}
}
Which returns:
from Test
from Test
from SubClass
Upvotes: 2