java 如何从另一个类调用方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35731043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:31:27  来源:igfitidea点击:

How do I call a method from another class?

javabluej

提问by Jen Fisher

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.

我试图调用的方法名称 public void printMenu()...在一个名为FoodMenu.

回答by Guy

Create an instance of FoodMenuand use it to call printMenu()

创建一个实例FoodMenu并使用它来调用printMenu()

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

回答by ΦXoc? ? Пepeúpa ツ

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

您将需要FoodMenu类的对象, 然后您可以调用该方法

Do someting like:

做一些像:

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

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

如果您的类FoodMenu在另一个包中,则将其导入您要定义对象的类中。

回答by mo sean

    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();
    }
    }

FoodMenuobject created by newkeyword And with help of object you can call its method f.printMenu();

FoodMenunew关键字创建的对象 在对象的帮助下,您可以调用它的方法f.printMenu();