How to call an inner class method from static main () method

Trying to create 1 interface and 2 specific classes inside the parent class. This will qualify the included classes as 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'm not sure how to create an object of class C inside the static main () method and call the method to call class C (). Right now I am getting problems in the line: A a = new C();

+4
source share
3 answers

Here, the inner class is not static, so you need to instantiate the outer class, and then call a new one,

 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() 
+5
source

To create an instance of an inner class, you must first create an instance of the outer class. Then create an internal object inside the external object using this syntax:

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

So you need to use:

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

Refer to the Java Tutorial .

+4
source

You have to do it

  A a = new Test2().new C(); 
+1
source

Source: https://habr.com/ru/post/1484764/


All Articles