I've searched and searched, and I feel like I'm missing something really minor about the steps of using them.
Class file for the generic:
public class Point <T> {
private T xPos, yPos;
public Point(T xPos, T yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
public T getXPos() {
return xPos;
}
public void setXPos(T xPos) {
this.xPos = xPos;
}
public T getYPos() {
return yPos;
}
public void setYPos(T yPos) {
this.yPos = yPos;
}
}
Demo file:
public class PointTester {
public static void main(String[] args) {
Point<Integer> point1 = new Point<Integer>(10,20);
Point<Double> point2 = new Point<Double>(14.5, 15.6);
Point<String> point3 = new Point<String>("topleftx", "toplefty");
System.out.println(point1);
System.out.println(point2);
System.out.println(point3);
}
}
To define how a class in printed, you need to override the standard toString()
method. In your example, you'd do something like
public String toString() {
return "(" + xPos + ", " + yPos + ")";
}
I assume that it is printing 'something' but that the 'something' is un-helpful.
I believe that the thing that you are missing is a 'toString' method.
You need to override the the toString
in Point
that will return what you want to print.
eg
@Override
public String toString() {
return /* what you want ... */;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.