AndroidDev AndroidDev -4 years ago 130
Java Question

Override toString() but the data type is Integer

When I run this code the output is (MyInt@15db9742)-Object Address-:

public static void main(String[] args) {
MyInt myInt = new MyInt(2);
System.out.println(myInt);
}

class MyInt {
public int val;
public MyInt(int val){
this.val = val;
}
}


What I want to do is: to print the val without myInt.val

I tried to override toString()?!

public String toString(){
return ""+val;
}


and it works! But I want the return type to be int/Integer NOT String, and there is a compiler error


The return type is incompatible with Object.toString()"


when I change the return type to int. Is there a way to do that?

EDIT:

In Short:

Integer integer = new Integer(5);
int INT = integer;
System.out.println(INT);


So I want myClass "MyInt" works Like class "Integer"
so I can assign int val directly

MyInt myInt = new MyInt(5);
int INT = myInt; // I don't need to type "myInt.val"
System.out.println(INT);

Answer Source

You seem to have misunderstood what happens behind the scenes when you call this:

System.out.println(myInt);

The println method takes an Object argument and then calls the .toString() method on that object. The toString() method always returns a string. Therefore what you did (return a string) was correct.

Note that when you do this:

System.out.println(1);

then there is an overload of println specifically for int arguments. But you can't pass an Object to println and expect it to be treated as a primitive type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download