如何解决与用户定义的方法和对象相关的 Java 中的以下错误?

How to solve following Error in Java related to user defined methods & objects?

我写了以下 Java 代码:

public class Point2D{
    private double xc, yc;
    
    public Point2D(double x, double y){
            this.xc = x;
            this.yc = y;
        }

    public Point2D createNewPoint(int xOff, int yOff){
        this.xc = xc + xOff;
        this.yc = yc + yOff;
        return xc;  
    }

    public static void main(String[] args){
        Point2D p1 = new Point2D(2.5, 3.5);

        Point2D p3 = p1.createNewPoint(5, -2);
        System.out.println(p3);
    }
}

我收到以下错误:

Point2D.java:27: error: incompatible types: double cannot be converted to Point2D
        return xc;  
               ^
1 error

谁能帮我解决这个错误,以及如何从 Java 中的用户定义方法中 return 两个 variables/values?

return 值的类型应与 return 类型匹配。您 returned xcdouble 类型,但 return 类型是 Point2D.

替换

public Point2D createNewPoint(int xOff, int yOff){
    this.xc = xc + xOff;
    this.yc = yc + yOff;
    return xc;  
}

public Point2D createNewPoint(int xOff, int yOff) {
    return new Point2D(xc + xOff, yc + yOff);  
}

此外,创建一个 toString 实现,如下所示,以便在打印 Point2D.

的对象时获得有意义的输出
public class Point2D {
    private double xc, yc;

    public Point2D(double x, double y) {
        this.xc = x;
        this.yc = y;
    }

    public Point2D createNewPoint(int xOff, int yOff) {
        return new Point2D(xc + xOff, yc + yOff);
    }

    @Override
    public String toString() {
        return "Point2D [xc=" + xc + ", yc=" + yc + "]";
    }

    public static void main(String[] args) {
        Point2D p1 = new Point2D(2.5, 3.5);

        Point2D p3 = p1.createNewPoint(5, -2);
        System.out.println(p3);
    }
}
  1. 为私有字段添加 getters

  2. Return一个新对象,如下面的解决方案,如果你想要一个新对象,可以从createNewPoint方法中得到

  3. 使用 getter 方法访问各个值。

     class Point2D {
     private double xc, yc;
    
     public Point2D(double x, double y){
             this.xc = x;
             this.yc = y;
         }
    
     public Point2D createNewPoint(int xOff, int yOff){
         return new Point2D(this.xc + xOff, this.yc + yOff);  
     }
    
     public double getXc() {
         return xc;
     }
    
     public double getYc() {
         return yc;
     }
    
     public static void main(String[] args){
         Point2D p1 = new Point2D(2.5, 3.5);
    
         Point2D p3 = p1.createNewPoint(5, -2);
         System.out.println (p3.getXc() + ":" + p3.getYc());
     }
    

    }