-1

I don't understand some example in Java.

public class Pair {
  private int a;
  private int b;
  public Pair(){

  }

  public Pair(int x, int y) {
    a = x;
    b = y;
  }

}

Second class

   public class First extends Pair {
     public First(int x, int y) {
       super(x,y);
     }

     public static void main(String[] args) {
       Pair pair = new Pair(10,11);
       String s = "It is equal " + pair;
       System.out.println(pair);
     }

 }

Because it's used concatenation of strings, automatically it will be called method toString() from class Pair, so the result should be: "It is equal (10,11)". It prints me location in memory why?
Maybe I should call method like:

public void show(){
System.out.println(a + "" + b);
}

However in example there isn't method show(), there is only String s like above.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
MatL
  • 39
  • 1
  • 9

3 Answers3

1

This is right as jvm is calling default implementation of toString from object class which prints the identity hashcode. if you want the output like this then you can override toString() method inside Pair class like below:

@Override
protected String toString{
    return "("+a+","+b+")";
}

After implementing this you will get the expected result as you have overriden the toString() method.

It's recommended approach to override the toString method as it helps in debugging and provide the meaningful logs.

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19
0

Since you didnt override ToString() method of class, it will be calling the Object class toString() which itself gives you the meomory location of Object.

So the solution is you have to override the toString() in your class and put your required snippet there, so that at time of printing the object ref. your overridden toString() will be called and expected outcome will be displayed.

Thanks

Neeraj
  • 171
  • 2
  • 11
0

Overide toString with your expected result in your Pair class. Like

@Override
    public String toString() {
        int c=a+b;
        return "Pair =" + c;
    }
Tanu Garg
  • 3,007
  • 4
  • 21
  • 29