I have a class (Point2D), and an instance variable (double tav) in this class.
I would like to compare different Point2D objects (based on variable "tav") by the relational operators (<,>).
(a < b) means that (a.tav < b.tav).
Is there any way to solve this problem?

public class Point2D
{
    private int x;
    private int y;
    private double tav;

    Point2D()
    {
        this.x=Integer.parseInt(JOptionPane.showInputDialog("x"));
        this.y=Integer.parseInt(JOptionPane.showInputDialog("y"));
        tav = Math.sqrt(Math.pow(x,2) + Math.pow(y,2));     
    }
}


public class Hf2
{
    public static void main(String[] args)
    {
        Pont2D a = new Pont2D();
        Pont2D b = new Pont2D();
        if(a<b)                     //It is wrong, I would like to solve this.
        {
            System.out.println("Bigger");
        }
    }
}

Recommended Answers

All 3 Replies

Is there any way to solve this problem?

Write a method to do what you want. Not much syntax candy in java. You can't hide the code that needs to be executed.

Unlike C++, you cannot override the primitive relation operators in Java. You would need to implement methods like this:

class X
{
    bool isLessThan( const X rhs ) ( ... return trueorfalse; }
    bool isGreaterThan( const x rhs ) { ... return trueorfalse; }
}

Don't invent your own mwthod signatures. Look at the Comparable interface in the API doc. If your class implements its compareTo method then you have a standard way of comparing your objects. This is how the standard sort methods work as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.