gpt4 book ai didi

java - Java 中出现 NullPointerException 错误

转载 作者:行者123 更新时间:2023-12-01 07:47:07 25 4
gpt4 key购买 nike

我有一个名为 Square 的类,它继承了一个名为 Shape 的类。在我的主要部分,我像这样实例化它:

Point p1 = new Point(3,3); 

Shape s1 = new Square(p1,3);

编译时出现以下错误:

Exception in thread "main" java.lang.NullPointerException
at Shape.<init>(Shape.java:19)
at Square.<init>(Square.java:18)
at mine.main(mine.java:16)

我有一个名为 Shape 的父类(super class),其实现如下:

  abstract class Shape implements Comparable<Shape> {
public Point position;

public Shape(Point p){
position.x = p.x; //Line 19
position.y = p.y;
}
}

点是以下类:

public final class Point {
public double x;
public double y;

// constructor that sets the values of x and y
public Point(double num1, double num2)
{
this.x = num1;
this.y = num2;
}
}

Square 是以下类:

class Square extends Shape {
private double side; // side is the side length

public Square(Point p0, double side)
{
super(p0); // Line 18
this.side = side;
}

最佳答案

您从未在Shape类中初始化position

你可能想做的事情

public Shape(Point p){
position = p;
}

或者,至少(如果您想“克隆”Point)

public Shape(Point p){
position = new Point(p.x, p.y);
}

关于java - Java 中出现 NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49646617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com