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

2019-09-01 21:00发布

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.

标签: java bluej
3条回答
对你真心纯属浪费
2楼-- · 2019-09-01 21:10

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

FoodMenu foodMenu = new FoodMenu();
foodMenu.printMenu();
查看更多
Viruses.
3楼-- · 2019-09-01 21:15
    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();

查看更多
等我变得足够好
4楼-- · 2019-09-01 21:28

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.

查看更多
登录 后发表回答