Can a main() method of class be invoked from another class in java

前端 未结 6 2068
春和景丽
春和景丽 2020-12-01 07:24

Can a main() method of class be invoked in another class in java?

e.g.

class class1{

  public static void main(String []args){

  }

}         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 07:59

    As far as I understand, the question is NOT about recursion. We can easily call main method of another class in your class. Following example illustrates static and calling by object. Note omission of word static in Class2

    class Class1{
        public static void main(String[] args) {
            System.out.println("this is class 1");
        }    
    }
    
    class Class2{
        public void main(String[] args) {
            System.out.println("this is class 2");
        }    
    }
    
    class MyInvokerClass{
        public static void main(String[] args) {
    
            System.out.println("this is MyInvokerClass");
            Class2 myClass2 = new Class2();
            Class1.main(args);
            myClass2.main(args);
        }    
    }
    

    Output Should be:

    this is wrapper class

    this is class 1

    this is class 2

提交回复
热议问题