开发者

Why do I receive a "cannot find symbol" error when compiling this interface method?

开发者 https://www.devze.com 2023-04-08 22:31 出处:网络
I\'m using the interface Place: public interface Place { int distance(Place other); } But when I try to implement the interface and compile the followi开发者_运维知识库ng code, a \"cannot find symb

I'm using the interface Place:

public interface Place
{
    int distance(Place other);
}

But when I try to implement the interface and compile the followi开发者_运维知识库ng code, a "cannot find symbol - variable xcor" error returns.

public class Point implements Place
{
    private double xcor, ycor;

    public Point (double myX, double myY)
    {
        xcor = myX;
        ycor = myY;
    }

    public int distance(Place other)
    {
        double a = Math.sqrt( (other.xcor - xcor) * (other.xcor - xcor) + (other.ycor - ycor) * (other.ycor -ycor) ) + 0.5;
        return (int)a;
    }

}

Any ideas for what I might be doing wrong? Does it have something to do with the scope of the fields?


The interface Place has no member xcor. Add a method double getXcor() to your interface and implement it in your class. The same applies to ycor. Then you can use these getters in your implementation of the distance method.

public interface Place
{
    int distance(Place other);
    double getXcor();
    double getYcor();
}


It is because the Place interface doesn't expose a symbol named 'xcor'. It only exposes the method 'distance'. so when you have a variable of type Place the compiler doesn't know which underlying type it is. You either have to have Place expose a getter for xcor/ycor etc or downcast the instance of 'Place' to 'Point'. downcasting is usually frowned on when you have multiple implementations of Place, but this is the usual problem with having an interface that overlays implementations that have different underlying properties. Like having a 'Shape' that has 'area()' with implementations of Rectangle and Circle that use different methods of computing area.


A Place does not have an xcor and ycor members, a Point does.


The parameter to the distance method is a Place, not a Point. Only the Point class has a field named xcor.


Several earlier posters mention the problem, which is that distance is being given a Place that has no xcor. I'm going to go a little further and suggest this is a place for generics. It probably makes no sense to define a distance function between arbitrary places. (If it does, then xcor and ycor can be pulled up into an abstract class between Place and Point.)

public interface Place<T> {
   int distance (Place<T> other);
}

class Point implements Place<Point> etc.
0

精彩评论

暂无评论...
验证码 换一张
取 消