简体   繁体   English

Java-在另一个类中使用包的main方法

[英]Java - Use main method of a package in another class

Let's say I have a package called com.Gazzali and inside this package I've 3 another classes. 假设我有一个名为com.Gazzali的软件包,并且在此软件包中还有3个其他类。

package com.Gazzali;
//Driver class
public class Main {

public static void main(String[] args) {
    System.out.println("Hey There !");
    FireCall target = new FireCall(); // calls 2nd class (named: Firecall)
    target.callfired();
 }
}

2nd class: 二等班:

package com.Gazzali;

public class FireCall {
   public void callfired()
   {
    System.out.println("Calling function Triggered.");
    Execute Fire = new Execute(); //calls 3rd class (named : Execution).
    if(Fire.click() == 1)
        System.out.println("You're Dead, Boy !!!");
    else
        System.out.println("Whoooss Saved !!!");
    }
 }

3rd class: 第三类:

package com.Gazzali;
import java.util.Scanner;

public class Execute {
int choice;
Scanner query = new Scanner(System.in);

public int click()
{
    System.out.println("Enter a choice : ");
    choice = query.nextInt();
    if(choice % 2 == 0)
    {
        return 1;
    }
    else
        return 0;
}
}

these 3 comprises my com.Gazzali package. 这3个组成了我的com.Gazzali软件包。 Now in another file ( RunPackTest.java ) I want to call the main method of Main class (Driver class). 现在在另一个文件( RunPackTest.java )中,我想调用Main类(Driver类)的main方法。 So I tried importing like below: 所以我尝试像下面这样导入:

import com.Gazzali.Main;
public class RunPackTest {
public static void main(String[] args) {
    Main run = new Main(); //calling Main method of Driver class of the package 
    System.out.println(run); //Doesn't seem to work,IDE only return 0 
}

}

How to do this? 这个怎么做? beacuse the main method of Main class starts the program and calls another classess of the package accordingly. 因为Main类的main方法启动程序并相应地调用包的其他类。

I believe this would do it: 我相信这可以做到:

import com.Gazzali.Main;

public class RunPackTest {
    public static void main(String[] args) {
        Main.main(null);
    }
}

You can call main just like any other method, although it's not good practice in general. 您可以像其他任何方法一样调用main ,尽管通常这不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM