java—在自定义类中使用接口

waxmsbnn  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(336)

此问题已在此处找到答案

什么是nullpointerexception,如何修复它((12个答案)
两天前关门了。
我正在编写一个代码,它取两个点,确定两个点的大小,比较它们,然后返回哪个更大。我有我的主类和方法来运行所有东西,然后还有另一个类点来实现我的接口。但是,我无法使从接口调用的方法正常工作。我的代码是:

public class A7 {
    public static void main(String[] args) {
        Relatable p1 = new Point(1,2);
        Relatable p2 = new Point(2,3);
        System.out.println(p1.isLargerThan(p2));
    }
}

class Point implements Relatable {
    private int x;
    private int y;
    private Point p1;
    private Point p2;

    public Point() {
        x = 0;
        y = 0;
    }
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public void setX(int x) {
        this.x = x;
    }
    public void setY(int y) {
        this.y = y;
    }
    public int getX() {
        return this.x;
    }
    public int getY() {
        return this.y;
    }
    public double getMagnitude() {
        double magnitude = Math.sqrt(this.x * this.x + this.y * this.y);
        return magnitude;
    }
    @Override
    public int isLargerThan(Relatable other) {
        if(p1.getMagnitude() > p2.getMagnitude()) {
            return 1;
        } else if(p1.getMagnitude() < p2.getMagnitude()) {
            return -1;
        } else {
            return 0;
        }
    }
}

interface Relatable {
    int isLargerThan(Relatable other);
}

当我尝试运行此程序时,会出现错误“线程“main”java.lang.nullpointerexception中的异常:无法调用“point.getmagnitude()”,因为“this.p1”为null“有人知道我可以解决此问题的方法吗?

3pvhb19x

3pvhb19x1#

有这两个变量点p1和点p2是没有意义的。因此,我删除了这两个变量并重写了代码。比较的重点是比较在a7类的main方法中创建的两个对象,即relatable p1和relatable p2。所以更改了方法islargerthan的代码来比较这两个对象(relatable p1和relatable p2),并在接口中添加了此方法。看一看

public class A7 {
public static void main(String[] args) {
    Relatable p1 = new Point(1,2);
    Relatable p2 = new Point(2,3);
    System.out.println(p1.isLargerThan(p2));
 }
}

class Point implements Relatable {
private int x;
private int y;

public Point() {
    x = 0;
    y = 0;
}
public Point(int x, int y) {
    this.x = x;
    this.y = y;
}
public void setX(int x) {
    this.x = x;
}
public void setY(int y) {
    this.y = y;
}
public int getX() {
    return this.x;
}
public int getY() {
    return this.y;
}
public double getMagnitude() {
    double magnitude = Math.sqrt(this.x * this.x + this.y * this.y);
    return magnitude;
}
@Override
public int isLargerThan(Relatable other) {
    if(this.getMagnitude() > other.getMagnitude()) {
        return 1;
    } else if(this.getMagnitude() < other.getMagnitude()) {
        return -1;
    } else {
        return 0;
    }
 }
}

interface Relatable {
  int isLargerThan(Relatable other);
   double getMagnitude();
}

相关问题