Reputation: 21
I have a question about constructors, if I make a contructor like:
Point originOne = new Point(23, 94);
if I have understood it correctly the originOne will be pointing to 23 and 94.
When i try to print it with System.out.println(originOne) i dont get these values, how come?
Thanks in advance! =)
Upvotes: 1
Views: 99
Reputation: 298
Try this:
System.out.println(originOne.getX() + " " + originOne.getY());
Upvotes: 0
Reputation: 117665
Assuming Point
is not java.awt.Point
.
You need to override toString()
of Point
class, since one of the overloaded methods of PrintStream#println()
(System.out is a PrintStream
) takes an object as a parameter, uses the object's toString()
to get a string representation of the object, and then prints it:
java.io.PrintStream#println(Object):
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
java.lang.String#valueOf(Object):
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Overriding the class is as simple as adding the method and its implementation within it:
@Override
public String toString() {
return "x = " + x + " - y = " + y;
}
Upvotes: 0
Reputation: 2066
Try this
Override toString
method. See below for your case
package test;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Point point = new Point(23, 94);
System.out.println(point);
}
@Override
public String toString() {
return "x : " + x + " y: "+ y;
}
}
Upvotes: 0
Reputation: 1309
I'm pretty sure you can override the toString() function of your class Point to make it print just like you want it to. Example:
@Override
public String toString() {
return this.X + "IEATBABYCLOWNS" + this.Y;
}
Upvotes: 2
Reputation: 33283
API description of java.awt.Point.toString():
Returns a string representation of this point and its location in the (x,y)
coordinate space. This method is intended to be used only for debugging
purposes, and the content and format of the returned string may vary between
implementations. The returned string may be empty but may not be null.
As you can see, the output depends on which JVM you use, and you are not guaranteed to get what you want.
I would change the println to something like:
System.out.println("[" + originOne.getX() + ", " + originOne.getY() + "]")
Upvotes: 0
Reputation: 10249
System.out.println(originOne);
This calls the toString method of the class of that object. And since you didnt override it, it calls the toString of the Object class.
Upvotes: 0