As an example, I want to mimic the functionality of the String object:
String mystring = new String ( "Hi there." );
System.out.println(mystring); // prints "Hi there." without calling any methods on String
// (that is what I want with my object)
System.out.println(mystring.toUpperCase()); // prints "HI THERE."
Starting with this:
class MyObject
{
private Int value ;
public MyObject ( Int value )
{
this.value = value ;
}
public Int getValue ( )
{
return this.value ;
}
public Int multiplyBy ( Int multiplier )
{
return this.value * multiplier ;
}
}
… How (or can I) do something like this:
MyObject myobject = new MyObject ( 6 ) ;
System.out.println( myobject ) ; // want to print myobject.value (6)
System.out.println( myobject.multiplyBy ( 2 ) ) ; // print 12
I’m quite new to Java and realize that I’m probably missing some fundamental concept, but any feedback would be appreciated. Thank you.
Edit:
The responses about overriding the toString method were helpful, but it’s not quite doing what I had in mind, here’s a better example of what I want:
Double mydouble = new Double ( 20.1 ) ;
System.out.println ( mydouble + 10.1 ) ; // prints 30.2
How would I do this with my own object (assuming I want the default value to be a double)?
Thanks again.
Final Edit (hopefully):
Your answers were enough to lead me to learn more about Primitive Wrappers and Autounboxing. My understanding is that there’s no way to do what I want (which at this point, I would describe as autounboxing my object as a double), or at least I’ll save that for another question. Cheers.
Yes, you can do it: all you need to do is overriding
toString:This works because
printlncallstoStringon objects being printed.