I'm writing a program our professor has given us as homework.
I have a class called Car
, that has two private real members x
and y
, which are supposed to represent the coordinates of the car in the coordinate plane, and I wanted to implement an interface called MyInterface
, in which I declared a method public boolean compare(Object t)
. It was stated it has to be Object t
and not something else, so that I can implement the interface in multiple classes (part of the homework). Java is the programming language in question.
The part of the code that that is problematic looks like this:
public interface MyInterface {
public boolean compare(Object t);
}
public class Car implements MyInterface{
private double x, y;
@Override
public boolean compare(Car t) {
double curdist = Math.sqrt(this.x*this.x + this.y*this.y);
double givdist = Math.sqrt(t.x*t.x + t.y*t.y);
if(curdist < givdist) return true;
else return false;
}
}
My method compare
needs to calculate the distances from the point (0,0) for the current car and the given car, and compare the two distances. If the current car's distance ( curdist
) is closer from the given car's distance ( givdist
) to (0,0), compare
returns true, otherwise it returns false.
My question is, how do I correctly implement this method in the class Car? I've tried a few things, but none of them seem to work out. Any help is appreciated, 'cause I am quite new to object-oriented programming. Thanks in advance.
If you must have Object
as the parameter type for compare
, then you must test the class of the parameter passed in to make sure it's a Car
first.
Change the compare
argument to Object
in your Car
class. Then the @Override
annotation will determine that the method is properly overriding the instance method, and you won't get a compiler error. Use the instanceof
operator to determine if t
is a Car
. You may decide to throw an IllegalArgumentException
if it isn't a Car
, or if it's null
. Then you can cast it to a Car
and continue with the logic of your method.
Even if you have to do have it take Object
for your class, a better way to do this in general is with generics. Here, this would answer the question "What is this class comparable to ?". If you've covered generics, then you may understand a class that is defined as MyInterface<T>
. The compare
method would take a parameter of type T
. This allows you to implement the method in Car
with a parameter of type Car
, provided Car implements MyInterface<Car>
. This is similar to the existing Comparable
interface built-in to Java.
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.