-2

My assignment is to create a program that simulates a simple online shopping program. we have to: create a main menu with 3 options and then a submenu when selecting the 2nd option on the main menu.

I'm unsure how call a method from another class for example:

I have been given a method:

public void start() {

which is in the file "GroceryStore.java"

I am supposed to create a topMenu method which when the user inputs "1" calls to the method:

public void displayItems(){

^in file called "Stock.java"

which then prints out an array of items that online store has in stock. The array in the Stock.java is

private SalesItem[] items;

Can anyone tell me how to do this? I have to do this for several things and I'm hoping I can apply the skeleton of this to the rest of the cases.

4

4 回答 4

2

现在,我将假设它是一个实例类型(它听起来像一个实例类型),并且您将引用 1 个或多个项目 是Stock有道理的。GroceryStoreStock


Stock的 s 必须用new关键字实例化。所以

Stock myStock = new Stock(/*parameters for constructor*/);

这样做之后,您可以调用like的displayItems方法myStock

myStock.displayItems(); 
于 2013-05-15T17:43:29.663 回答
1

要在当前实例之外调用方法,您有多种选择:

  • 制作方法static(这样它就不会附加到任何特定实例)并通过调用它MyClass.method(),如果它是无状态对象,这很有意义,主要是实用方法
  • 创建一个可以访问的静态实例变量(因此方法不是静态的,而是特定对象是),然后通过调用它SomeClass.stock.method(),当您在整个程序中需要特定类型的单个对象时,这很有意义
  • 在要从中调用方法的类中创建一个普通的实例变量(这仅在包含的对象用于HAS-A关系时才有意义)。然后你称之为简单地做this.stock.method()(你可以省略this
于 2013-05-15T17:43:36.840 回答
1

所以 start() 在 GroceryStore 类中。

所以在公共静态无效主类中,你会去:

GroceryStore gs = new GroceryStore();
gs.start();

在您的 GroceryStore 类中,您将有一个看起来像这样的新方法(您可能希望在 GroceryStore 对象的构造函数中有 Stock stock = new Stock() 行——这更有意义:

Stock stock = new Stock();
public void topMenu(int parm){
   if(parm==1)then{
      stock.displayItems();
   }
}

最后在 Stock 类中,您可以使用 displayItems 方法,该方法可能如下所示:

public void displayItems(){
  for(int i=0;i<items.length;i++){
     SalesItem temp = items[i];
     System.out.prinlnt(temp.toString());//or this may be temp.getName() or whatever returns a string from this SalesItem object - I dont know what it looks like - you never said!

  }
}

但是,您必须真正了解这里发生的事情,而不仅仅是复制粘贴并运行?!在您调用 topMenu 方法并将其传递为 1 之前,这实际上不会做任何事情,因此您需要锻炼如何与 gs 对象进行交互,无论是通过键盘输入、鼠标单击 gui 还是其他方式: )

于 2013-05-15T17:49:25.113 回答
0

You need to tell the compiler where to get the methods from if the method is not in the same class. The best way of doing this would be to create an object that refers to the class you're trying to reach (using the New Java keyword and the appropriate syntax, i.e. ClassName objectName = new ClassName() - you may want to include any parameters you may have).

Have a look at this other StackOverflow answer - the user had a question very similar to yours, so it may help.

Also, there is a pretty good tutorial on objects and classes on TutorialsPoint. I suggest you have a look at it and give it a go. Try understanding the concept behind what you're trying to achieve first - I can guarantee you it will help later on as this is a very fundamental concept in OO programming.

于 2013-05-15T17:51:25.313 回答