0

I have a problem regarding that my program prints objects instead of string.

I have a class which is called constants.java

in it there is the following:

public interface constants
{
        String[] FIELD_NAMES =
            {
                "test1", "test2"
            };
}

In my main class i try to print these fields.

public void fillFields() {
        for (int i = 0; i < plate.length; i++) {
            // Det her er noget quick-and-dirty-fusk:
            switch (i + 1) {
                // Andre felter:
                case 1:
                    plate[i] = new OtherField(Constants.FIELD_NAMES[i], i + 1);
                    break;

                default:
                 plate[i] = new OtherField(Constants.FIELD_NAMES[i], i + 1);
}

and this is the main String print out function:

   public static void main(String[] args) 
   {
    System.out.println(plate[current.getPos()]);)
   }

the getPos is a number generator(lets say between 1 and 2) and the current is a player index, and i have checked it, and it is working. but when i fx. land on "otherField" plate, i get an output like: otherfield@1b6d3586

I think its because i am printing the object instead of the string, but how can i solve this?

chburd
  • 4,131
  • 28
  • 33
Andrew
  • 49
  • 10
  • 2
    You're printing the *address* of the object since the default `toString` of `Object` is called because you didn't override it (Since each object has `toString()` method, the default displays the class name *representation*, then adds `@` sign and then the hashcode) – Maroun Nov 17 '14 at 13:20
  • `switch (i+1)` why +1 ? Keep it simple and put `case 0` – Michael Laffargue Nov 17 '14 at 13:25
  • I found another solution too, but thanks! Greatfull that you could help :-) – Andrew Nov 17 '14 at 13:25
  • doh! Thanks! it's alot easier! – Andrew Nov 17 '14 at 13:28

2 Answers2

1

You are printing an instance of OtherField. You must override toString() in this class if you wish it to print something more meaningful. Otherwise, it simply uses the default implementation of Object::toString() class.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

I found a solution to this.

I was printing the whole object, so thats why i got the error.

I had a getName method in my other class which was linket Constants.FIELD_NAMES which i used to print the specific String.

so i used the method: plate[current.getPos()].getName()

Thanks guys!

Andrew
  • 49
  • 10