简体   繁体   English

如何从其他类调用变量和方法?

[英]How do I call variables and methods from other classes?

I'm doing a homework assignment, and I need to create methods in one class "coinDispenser", and call them in the main class, "HW1" 我正在做作业,我需要在一个类“ coinDispenser”中创建方法,并在主类“ HW1”中调用它们

I'm not sure how this works, however. 不过,我不确定这是如何工作的。 This is a sample of my code in coinDispenser.java: 这是我在coinDispenser.java中的代码示例:

private int numNickles = 0;

And then calling the method later in HW1.java: 然后稍后在HW1.java中调用该方法:

System.out.println("There are "+numNickles+" nickles in the machine.")

But I always get the error "numNickles cannot be resolved to a variable" and it wants me to create the integer in the HW1 class. 但是我总是收到错误“ numNickles无法解析为变量”,并且它希望我在HW1类中创建整数。

How do I call the integer from within HW1.java? 如何在HW1.java中调用整数? Changing the integer to public int type doesn't make any difference. 将整数更改为public int类型没有任何区别。

Well, you definitely can't access a private member variable from one class to another. 好吧,您绝对不能从一个类访问另一个类的私有成员变量。 In order to access a public member in a different class, you need to either make a static variable and reference it by class, or make an instance of CoinDispenser and then reference that variable. 为了访问其他类中的公共成员,您需要创建一个静态变量并按类引用它,或者创建一个CoinDispenser实例,然后引用该变量。

So, in CoinDispenser, it'd be: 因此,在CoinDispenser中,它将是:

public int numNickles = 0;

and in HW1, you'd have: 在HW1中,您将拥有:

CoinDispenser cd = new CoinDispenser();
System.out.println("There are "+ cd.numNickles + " nickles in the machine.")

If you did a static variable you could also do: 如果您做了一个静态变量,您也可以这样做:

CoinDispenser.numNickles

To call a method in another class, you have two options. 要调用另一个类中的方法,您有两个选择。

Option 1: 选项1:

You can declare the method to be called as static , which means that it doesn't need to be called on an object. 您可以将方法声明为static ,这意味着不需要在对象上调用该方法。

NOTE: If you take this route, (which you shouldn't; it's generally bad to use static methods), you have to declare numNickles as static , meaning that there is only one instance of this field no matter how many CoinDispenser objects you create. 注意:如果采用这种方式(不应该这样做;使用静态方法通常是不好的),则必须将numNickles声明为static ,这意味着无论您创建多少个CoinDispenser对象,此字段只有一个实例。

Example: 例:

static void methodToCallName(any arguments it takes) {
    //...do some stuff...//
}

Option 2: You can create an instance of the class using the new keyword which contains the method and call the method: 选项2:您可以使用包含方法的new关键字创建类的实例,然后调用该方法:

Example: 例:

// in some method in the HW1 class (Which is a horrible class name, see java conventions)

CoinDispenser dispenser = new CoinDispenser(any parameters here);

coinDispenser.whateverYourMethodIsCalled(any arguments it takes);

The whole idea of classes in an object oriented language is to keep separate things separate. 面向对象语言中类的整体思想是使单独的事物保持分离。 When you reference a variable defined in another class, you have to tell the program where it is. 当您引用另一个类中定义的变量时,必须告诉程序它在哪里。

I get the sense that you haven't really learned what it means to be object oriented, and you really should look more into it. 我觉得您还没有真正了解面向对象的含义,因此您应该更多地研究它。 You can't fake it; 你不能伪造它。 there is NO getting around object orientation. 没有绕过面向对象的方向。 You must learn to love it. 您必须学会爱它。 Sure, it can make simple things hard, but it will make hard things soo simple. 当然,它会使简单的事情变得困难,但会使困难的事情变得如此简单。


For the second bits of your question... 对于您问题的第二部分...

Please note that numNickles should in fact be private, contrary to what other users are saying. 请注意,实际上与其他用户所说的相反, numNickles应该是私有的。

Java best practices advocate encapsulation, which is basically a principle saying that other parts of your program should only be able to see what they need to and the inner workings of each class should not be exposed to other classes. Java最佳实践主张封装,这基本上是一个原则,即程序的其他部分应该只能看到它们需要的内容,并且每个类的内部工作都不应暴露给其他类。

How do you achieve this? 您如何实现的? Simple; 简单; use accessor and mutator methods (getters and setters) to access and modify your fields. 使用访问器和更改器方法(获取器和设置器)访问和修改您的字段。

// Define your field like usual...
private int numNickles = 0;

// ...and add these two methods...
public void setNumNickles(int value) {
    numNickles = value;
}

public int getNumNickles() {
    return numNickles;
}

This may seem like a lot of work for a variable, but many IDE's will automate the process for you, and it will save you from many frustrating bugs in the long run. 对于变量来说,这似乎需要做很多工作,但是许多IDE会为您自动执行该过程,从长远来看,它将使您免受许多令人沮丧的错误的困扰。 Get used to it, because the rest of the Java world does it. 习惯它,因为Java世界的其余部分都做到了。

If numNickes is in another class you can't call it since it is scoped private. 如果numNickes在另一个类中,则不能调用它,因为它的作用域是私有的。

If you want access to private scoped variables you have to write a method to return it. 如果要访问私有作用域变量,则必须编写一个方法将其返回。 The convention is typically 该约定通常是

public int getNumNickles(){
    return numNickles;
}

This is by design and allows the protection of variables that you do not want to expose. 这是设计使然,可以保护您不想公开的变量。

Your output would then be System.out.println("There are "+myclass.getNumNickles()+" nickles in the machine.") 然后,您的输出将是System.out.println(“机器中有” + myclass.getNumNickles()+“刻痕。”)

Alternatively you could make the variable public 或者,您可以将变量公开

public int numNickels;

But now it can be read from, and written to, by anyone using the class. 但是现在,使用该类的任何人都可以读取和写入该文件。

You are trying to access the field named numNickles from your CoinDispenser class (BTW CoinDispenser is the correct name for your java class). 您正在尝试从CoinDispenser类访问名为numNickles的字段(BTW CoinDispenser是Java类的正确名称)。 You can not directly access the fields and methods in your HW1 class. 您不能直接访问HW1类中的字段和方法。 So, as MadProgrammer has indicated in the comment under your question, follow along as that. 因此,正如MadProgrammer在您的问题下的注释中所指出的那样,请按照以下说明进行操作。

In your HW1.java class have something like: 在您的HW1.java类中,类似以下内容:

CoinDispenser cd = new CoinDispenser(); 
System.out.println("There are "+cd.getNumNickles()+" nickles in the machine.");

The "cd" in above line of code is your handle on the CoinDispenser class. 上面的代码行中的“ cd”是您在CoinDispenser类上的句柄。 With cd, you can access (by dotting) fields and methods from any class where you use the above lines. 使用cd,您可以从使用上述各行的任何类中访问(通过打点)字段和方法。 Further, you will still not be able to access the fields and methods in your CoinDispenser class if those fields and methods are "private". 此外,如果这些字段和方法是“私有的”,您仍将无法访问您的CoinDispenser类中的字段和方法。

The standard way to access a private field in another class is to use a getter method. 访问另一个类中的private字段的标准方法是使用getter方法。

This would be like 这就像

private int numNickles = 0;
public int getNumNickles () {
   return numNickles;
}

Also useful would be a setter method setter方法也很有用

public void setNumNickles (int numNickles) {
   this.numNickles  = numNickles;
}

Many IDE's (eg Eclipse) will automatically create these methods for you upon a click of a button. 单击按钮,许多IDE(例如Eclipse)将自动为您创建这些方法。

These methods can then be called upon an instance of a CoinDispenser class. 然后可以在CoinDispenser类的实例上调用这些方法。

CoinDispenser coinDispenser = new CoinDispenser ();
coinDispenser.setNumNickles (23);

System.out.println("There are "+ coinDispenser.getNumNickles() + " nickles in the machine.");

Java is an Object-Oriented Programming language. Java是一种面向对象的编程语言。 This means in essence, that everything is based on the concept of objects. 从本质上讲,这意味着一切都基于对象的概念。 These objects are data structures that provide data in the form of fields and methods . 这些对象是数据结构,以字段方法的形式提供数据。 Every class that you provide an implementation of, needs a form of an instance, to actually do something with it. 您提供的每个实现的类都需要一种实例形式,才能实际对其执行操作。

The following example shows that when you want to make an instance of a class, you need to make a call using new CoinDispenser(100) . 以下示例显示,当您要创建类的实例时,需要使用new CoinDispenser(100)进行调用。 In this case, the constructor of the class CoinDispenser requires one argument, the amount of coins. 在这种情况下,类CoinDispenser的构造CoinDispenser需要一个参数,即硬币数量。 Now to access any of the fields or methods of your newly made CoinDispenser, you need to call the method using variable.method() , so in this case coinDispenser.getCoins() to retrieve the title of our book. 现在要访问新制作的CoinDispenser的任何字段或方法,您需要使用variable.method()调用该方法,因此在本例中为coinDispenser.getCoins()来检索我们的书名。

public class CoinDispenser {
    private int coins = 100; // Set the amount of coins

    public int getCoins() {
        return coins;
    }
}

public class HW1 {
    public static void main(String[] args) {
        CoinDispenser coinDispenser = new CoinDispenser(100);
        System.out.println("I have " + coinDispenser.getCoins() + " left.");
    }
}

NB: We are using an extra method getCoins() , a getter, to retrieve the contents of the field coins . 注意:我们正在使用一种额外的方法getCoins() ,即一个getter,以获取字段coins的内容。 Read more about access level here . 在此处阅读有关访问级别的更多信息。

First of all, there is no variable name numNickels which cause the error to occur. 首先,没有导致错误发生的变量名numNickels。 Second, to access the attribute of the class coinDispenser, you will need to create an object of that class, that is 其次,要访问coinDispenser类的属性,您将需要创建该类的对象,即

coinDispenser a=new coinDispenser();

By doing so, you can then access public methods of the class coinDispenser. 这样,您就可以访问类coinDispenser的公共方法。 Considering that the attribute numNickles is private, you have two options, which is: 考虑到属性numNickles是私有的,您有两个选择,即:
1. Change numNickles to public, then access it using 1.将numNickles更改为public,然后使用

a.numNickles

2. Create a public method to get private attribute in class coinDispenser 2.创建一个公共方法以在coinDispenser类中获取私有属性

public int getNumNickles() {return numNickles;}

and access it from HW1 using 并使用HW1访问它

a.getNumNickles()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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