Search code examples
javaobjectgetter-settersetter

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

}

Solution

  • 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 i.e. 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);
    }