简体   繁体   中英

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"

I'm not sure how this works, however. This is a sample of my code in coinDispenser.java:

private int numNickles = 0;

And then calling the method later in 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.

How do I call the integer from within HW1.java? Changing the integer to public int type doesn't make any difference.

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.

So, in CoinDispenser, it'd be:

public int numNickles = 0;

and in HW1, you'd have:

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:

You can declare the method to be called as static , which means that it doesn't need to be called on an object.

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.

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:

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.

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.

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. Get used to it, because the rest of the Java world does it.

If numNickes is in another class you can't call it since it is scoped private.

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.")

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). You can not directly access the fields and methods in your HW1 class. So, as MadProgrammer has indicated in the comment under your question, follow along as that.

In your HW1.java class have something like:

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. With cd, you can access (by dotting) fields and methods from any class where you use the above lines. Further, you will still not be able to access the fields and methods in your CoinDispenser class if those fields and methods are "private".

The standard way to access a private field in another class is to use a getter method.

This would be like

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

Also useful would be a setter method

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.

These methods can then be called upon an instance of a CoinDispenser class.

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. 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) . In this case, the constructor of the class CoinDispenser requires one argument, the amount of coins. 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.

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 . Read more about access level here .

First of all, there is no variable name numNickels which cause the error to occur. Second, to access the attribute of the class coinDispenser, you will need to create an object of that class, that is

coinDispenser a=new coinDispenser();

By doing so, you can then access public methods of the class coinDispenser. Considering that the attribute numNickles is private, you have two options, which is:
1. Change numNickles to public, then access it using

a.numNickles

2. Create a public method to get private attribute in class coinDispenser

public int getNumNickles() {return numNickles;}

and access it from HW1 using

a.getNumNickles()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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