Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call inner class's method from static main() method

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();

like image 204
sunny_dev Avatar asked Jun 06 '13 05:06

sunny_dev


People also ask

How do you call an inner class from the main method?

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.

How do you call a static method from an inner class?

InnerClass inn = out. new InnerClass(); Then You can call any method in innerClass from this object. This will qualify the enclosing classes to be Inner classes.

Can we write inner class in main method?

main method in inner classes Inside inner class we can't declare static members. So that it is not possible to declare main() method inside non static inner class.

Can a class have a static inner class?

Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.


1 Answers

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()
like image 62
Qiang Jin Avatar answered Nov 15 '22 11:11

Qiang Jin