This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).
Related
I have a problem, the solution is probably very easy, but nothing comes to mind at the moment, so I am looking for a little help.
... so I have a problem with calling the method.
I have a Space 2D class:
public class Space2D {
//several other methods etc.
//for example I will take this method
public double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
and I want to call it in the SpaceTest class:
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D point2D = new Space2D();
// I also have a Space 3D class that inherits from the 2D class.
// but I want to call the distance method from the Space 2D class so I'll try to do it like this:
point2D.distance(3,4) // <-- wrong
}
}
I would like to put 3 and 4 after p1 and p2 from the distance method but I get a bug that I have to put integers in it if I want to do so, so my question what do I have to put in calling this method so that I can run it, i.e. what do I have to put for this object ?? "Space2D p1"?
point2D.distance (???)
Thank you in advance for your help and explanation, I hope you will help me understand this.
public double distance(Space2D p1, Space2D p2) {
...
This means when you invoke distance you have to pass in two objects of type Space2D.
point2D.distance(3,4) <-- wrong
You tried to invoke it with two integers, which is why you get the error. Points have an x and y coordinate, what does it even mean to ask for the distance between 3 and 4 if the domain is R2.
What you probably want is something like
int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));
That's because you're putting integers as parameter which is not allowing to take as parameter. Distance function takes distance(Space2D p1, Space2D p2) Space2D object.
You can use like this:
In Space2D Class :
public class Space2D {
private int x;
private int y;
public Space2D(int x, int y) {
this.x = x;
this.y = y;
}
//several other methods etc.
//for example I will take this method
public static double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
In SpaceTest class :
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
}
}
public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));
I'm writing a graphics library in Java, primarily for use in game development. It needs basic vector and matrix objects for use in 3D calculations, and ideally those objects would employ SIMD operations. Although Java doesn't provide such operations directly, it is possible to hint to the JVM to use them in the context of large arrays. Hence...
Can the JVM vectorize operations on vector-like objects? If so, how can I ensure that this happens?
To clarify: I need operations on small, statically sized objects, not variable-length arrays. E.g., matrices that are strictly 3x3 or 4x4, vectors that are strictly of length 4, etc. Vectorization of large, variable-length arrays has already been discussed.
Some example candidates for vectorization:
public class Vector4f
{
public int x, y, z, w;
public void madd(Vector4f multiplicand, Vector4f addend)
{
this.x = this.x * multiplicand.x + addend.x;
this.y = this.y * multiplicand.y + addend.y;
this.z = this.z * multiplicand.z + addend.z;
this.w = this.w * multiplicand.w + addend.w;
}
public float dot(Vector4f other)
{
return this.x * other.x
+ this.y * other.y
+ this.z * other.z
+ this.w * other.w;
}
}
public class Matrix44f
{
public float m00, m01, m02, m03;
public float m10, m11, m12, m13;
public float m20, m21, m22, m23;
public float m30, m31, m32, m33;
public void multiply(Matrix44f other) { ... }
public void transform(Vector4f other) { ... }
public void andSoOnAndSoForth() { ... }
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to access a private variable (x) in my method distanceFromPoint but it seems it doesn't work. How can I access it? My method is returning 0.0 all the time regardless of other values.
Code
public class Pointdeclare {
private static int x;
private static int y;
Pointdeclare (int x_ , int y_ ){
this.x = x_;
this.y = y_;
}
int getX(){
return x;
}
int getY(){
return y;
}
static double distanceFromZero (){
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
double distanceFromPoint(Pointdeclare point){
int distX = point.getX()- this.x;
int distY = point.getY()- this.y;
return (double) Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
}
}
Main Class
public class main {
static Pointdeclare p1 = new Pointdeclare(6, 7);
static Pointdeclare p2 = new Pointdeclare(3, 7);
public static void main (String[] args){
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}
This will work better for you:
package cruft;
/**
* Point2 description here
* #author Michael
* #link http://stackoverflow.com/questions/14087002/how-to-access-private-variables-in-a-java-class-method
* #since 12/29/12 6:52 PM
*/
public class Point2 {
private int x;
private int y;
Point2(int x_, int y_) {
this.x = x_;
this.y = y_;
}
int getX() {
return x;
}
int getY() {
return y;
}
double distanceFromZero() {
return distanceFromPoint(new Point2(0, 0));
}
double distanceFromPoint(Point2 point) {
int distX = point.getX()-this.x;
int distY = point.getY()-this.y;
return (double) Math.sqrt(Math.pow(distX, 2)+Math.pow(distY, 2));
}
public static void main(String[] args) {
Point2 p1 = new Point2(6, 7);
Point2 p2 = new Point2(3, 7);
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}
You shouldn't declare your class fields as static, just leave them private.
Btw consider using Point or Point2D native classes from java.awt.geom package.
You declared "x" and "y" static, which means that they're class variables, not instance variables.
Because of that, every new call to the constructor will overwrite the old values. Thus distanceFromPoint always returns zero because there's only one x and one y.
The problem is not due to private, instead, it's because of static. x is static. In your method, you should use x as:
int distX = point.getX()- Pointdeclare.x; // You could use this.x because x is static.
I hope you find this relevant, it doesn't answer your question directly but I was recently informed my understanding of static was incorrect so having just researched the topic I thought maybe I could help. Static variables belong to a class and not its objects, objects of a class may access a static variable but no matter how many objects of the class there are there will only be one copy of the static variable. So I think what the people before me were saying is instead of p1 and p2 having their own copies of x and y both objects share the same x and y field therefore your value returned is 0. In other worlds your trying to find the distance between one location, it will always be zero. Hopefully that helps :-). I'm sorry I missed the first line of the main method. p2 should return a value as long as it isn't zero but p1 will not.
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 7 years ago.
I have a list of point objects, which I want to sort by a certain coordinate, say the x-values. Does Java provide any useful mechanisms or should I avail myself of one of the common sort algorithms?
Yes create a custom Comparator , and use it to sort list of points
class Point{
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
}
}
List<Point> points = new ArrayList<Point>();
points.add(new Point(1, 2));
points.add(new Point(60, 50));
points.add(new Point(50, 3));
Collections.sort(points,new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return Integer.compare(o1.getX(), o2.getX());
}
});
In Point class you should implement Comparable interface with generic type <Point> and use Collections.sort (java.util package) for sorting List<Point>
Assume:
class Point implements Comparable<Point>{
int compareTo(Point other){ /* your logic */}
}
List<Point> list = new ArrayList<Point>();
/* adding points */
Collections.sort(list);
You should either make your point class to implement Comparable interface or provide sort() method with your own Comparator object, which tells sort() how to order your objects. There a lot of examples around here.
You can use something like a Bean Comparator so you don't have to keep creating custom Comparators.