简体   繁体   中英

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.

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. Now in another file ( RunPackTest.java ) I want to call the main method of Main class (Driver class). 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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