Search code examples
javaoopreturnuser-defined-functionsreturn-type

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


I have written following Java code:

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);
    }
}

I am getting following error:

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

Can someone help me out to solve this error and also how to return two variables/values from a user-defined method in Java?


Solution

  • The type of the return value should match the return type. You have returned xc which is of type, double but the return type is Point2D.

    Replace

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

    with

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

    Also, create a toString implementation something as shown below so that you can get a meaningful output when you print an object of 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);
        }
    }