简体   繁体   中英

How to set variable within Java class from within another class

I'm trying to set up a simple set of classes in Java in such a way that a specific Trader class (see below) can 'talk' to other Robot class objects, as identified by a customer id, and set an offer variable within it.

My intial attempt fails because I've defined customer as a String, which is why customer.receiveTender(target) won't work. But I also tried Agent and the Customer subclass but they don't work.

I'm very new to Java - can someone point me in the right direction?

public class Trader extends Robot {

    private String target;

    public String selectTarget(String target) {
        target = target;
    }

    public void issueOffer(String target, String customer) {
        customer.receiveOffer(target);
    }

}

UPDATE:

public class Robot {

    private String id;  

    public Robot() {
        id = "No name yet";
    }

    public void setID (String newID) {
        id = newID;
    }

    public String getID() {
        return id;
    }

}

public class Customer extends Robot {

    private String target;

    public void receiveOffer(String target) {
        target = target;
    }

}

Because, receiveTender() is not a member of String class.

Below line of code means an object with name customer , which is String type has method receiveTender and takes argument as String ie target . But, if you look at the String class, it doesn't have any method with name receiveTender and that's the reason. It won't compile.

customer.receiveTender(target);

As per your updated code, receiveOffer is a member of Customer class, which means you need to have instance of Customer class to access its method and that means it should be

public void issueOffer(String target, Customer customer) {
    customer.receiveOffer(target);
}

Majority of the times, one class can speak to another class only when the class has an object of another class. Inheritance come into picture for "is a" relationship. The Trader class written above will only make sense if Trader is a Robot otherwise create two separate classes as Robot and Trader.

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