6

Trying to create 1 interface and 2 concrete classes inside a Parent class. This will qualify the enclosing classes to be Inner classes.

public class Test2 { interface A{ public void call(); } class B implements A{ public void call(){ System.out.println("inside class B"); } } class C extends B implements A{ public void call(){ super.call(); } } public static void main(String[] args) { A a = new C(); a.call(); } } 

Now I am not really sure how to create the object of class C inside the static main() method and call class C's call() method. Right now I am getting problem in the line : A a = new C();

3 Answers 3

11

Here the inner class is not static, so you need to create an instance of outer class and then invoke new,

A a = new Test2().new C(); 

But in this case, you can make the inner class static,

static class C extends B implements A 

then it's ok to use,

A a = new C() 
Sign up to request clarification or add additional context in comments.

Comments

4

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); 

So you need to use :

A a = new Test2().new C(); 

Refer the Java Tutorial.

Comments

1

You should do this

 A a = new Test2().new C(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.