Pregunta

My professor just went over mutable and immutable, and gave us this coding exercise to complete. 1) Create a Customer object called customer with initial values of 1 and "Cust1" respectively.

2) Display the customer object to the screen using the toString() method.

3) Create a String object reference called name and assign to it the customer's name.

4) Assign the value "Bo Beep" to the object reference name.

5) Display the customer object to the screen using the toString() method.

The output should look like this.

Customer{id=1, name=Cust1}

Customer{id=1, name=Cust1}

I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.

Any input is helpful, thanks!

Here's my main class,

package hw01;


public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");


public static void main(String[] args) {
    System.out.println(customer);
    System.out.print(customer);

}
}

And here's my Customer class.

package hw01;

public class Customer {

private int id;
private String name;

public Customer() {
}

public Customer(int id, String name) {
    this.id = id;
    this.name = name;


}

public int getId() {
    return id;
}

public  String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer{" + "id=" + id + ", name=" + name + '}';
}

}
¿Fue útil?

Solución

Sounds like for #3 it should be something like this:

String name = customer.getName();

and then #4 would be:

name = "Bo Peep";

The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top