How do I call a method from another class? [closed

2019-09-01 21:27发布

问题:

I want to print a method that is in another class. How do I do that?

Thanks!

The method name I am trying to call is public void printMenu()... within a class called FoodMenu.

回答1:

Create an instance of FoodMenu and use it to call printMenu()

FoodMenu foodMenu = new FoodMenu();
foodMenu.printMenu();


回答2:

You will need an object of the class FoodMenu then you can call the method

Do someting like:

FoodMenu myFoodMenu = new FoodMenu(); // declaring the object
myFoodMenu .printMenu(); // calling the method.

if your class FoodMenu is in another package, then import it in the class you are going to define the object.



回答3:

    public class FoodMenu{
    public void printMenu() { 
    System.out.println("here is menu sir!"); 

}
     public static void main(String[] arg) {
    FoodMenu f = new FoodMenu();
    f.printMenu();
    }
    }

FoodMenu object created by new keyword And with help of object you can call its method f.printMenu();



标签: java bluej