-1

I'm very inexperienced with Java and have been assigned this

enter image description here

I am trying to do number 3 and 5, this is my code

import java.util.*;

public class Greeter {

    public Greeter(String aName) {
        this.name = aName;
    }

    public void setName (String name) {
        this.name = name;
    }

    public static Greeter getRandomInstance() {
        if (generator.nextBoolean())
            return venus;
        else
            return mars;
    }

    public void swapNames(Greeter other) {
        String temp = this.name;
        this.name = other.name;
        other.name = temp;
    }
        
    public String sayHello() {
        return "Hello, " + name + "!";
    }

    private static Greeter venus = new Greeter("Venus");
    private static Greeter mars = new Greeter("Mars");
    private String name;
    private static Random generator = new Random();

}

This is test class

public class GreeterTester {

    public static void main(String[] args) {

        Greeter temp = new Greeter("Madi");
        Greeter name1 = temp;
        Greeter name2 = temp;
        String temp1 = name1.sayHello();
        name2.setName("Grace");
        System.out.println("Name 1: " + name1);
        System.out.println("Name 2: " + name2);
    }
}

But instead of the names, it is printing Greeter@33c7353a I have been searching for how to do this assignment for hours and I am still very confused so I apologize if this is all completely wrong in the first place. Some advice would be very appreciated.

Shubham Srivastava
  • 1,673
  • 1
  • 8
  • 17
madi
  • 3
  • 2
  • What is the logic by which you expect the names to be printed? The `Greeter` instance does not care about the name of the variable you used for it. – Karl Knechtel Sep 22 '20 at 03:51

1 Answers1

1

To change string presentation of class you have to override toString() method in this class

@Override
public String toString(){
   return name;
}
Autocrab
  • 3,119
  • 1
  • 13
  • 15