1

I'm trying to create two static objects of class Test: CAT and DOG. I want them to be able to have different output int talk() method:

public class HelloWorld
{
  public static void main(String[] args)
  {
    System.out.println("Hi");

    Test.DOG.talk();  //"I am a cat" output
  }
}

class Test  {
    public static Test DOG = new Test("I am a dog");
    public static Test CAT = new Test("I am a cat");

    public static String talkString;

    private Test(String text)  {
        talkString = text; 
  }

  public static void talk()  {
        System.out.println(talkString); 
  }
}

However the CAT object overwrites the talkString therefore the DOG can no longer use it. Is there a way around it, while keeping DOG and CAT static themselves?

Ans
  • 1,212
  • 1
  • 23
  • 51
  • 2
    `public static String talkString;` <-- remove the `static`. – Andy Turner Jun 05 '18 at 08:06
  • @Andy Turner But then my code wouldn't be valid: the DOG and CAT would *require* an object, to use a `talkString` – Ans Jun 05 '18 at 08:13
  • So... perhaps remove another `static`? – Andy Turner Jun 05 '18 at 08:15
  • @Andy Turner which one? I want DOG and CAT to remain static. – Ans Jun 05 '18 at 08:16
  • There are 5 statics in your code. I've said that one should be removed specifically. How long would it take you to try the other 4? (Tip: *read the duplicate* so that you can understand what you're actually doing; also try searching for the compiler error you get if you just remove the `static` on `talkString`) – Andy Turner Jun 05 '18 at 08:17
  • @Andy Turner sovled it, thanks. – Ans Jun 05 '18 at 08:24

0 Answers0