【问题标题】:call a method in class, inheritance调用类中的方法,继承
【发布时间】:2021-06-17 20:44:38
【问题描述】:

我有一个问题,解决方案可能很简单,但目前没有任何想法,所以我正在寻求帮助。

...所以我在调用该方法时遇到了问题。

我有一个 Space 2D 课程:

    public class Space2D {
    
    //several other methods etc.
    
    //for example I will take this method

    public double distance(Space2D p1, Space2D p2) {
            double dx = p1.x - p2.x;
            double dy = p1.y - p2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }
    }

我想在 SpaceTest 类中调用它:

public class SpaceTest extends Space3D {
    public static void main(String[] args) {
    Space2D point2D = new Space2D();

    // I also have a Space 3D class that inherits from the 2D class.
    // but I want to call the distance method from the Space 2D class so I'll try to do it like this:

    point2D.distance(3,4) // <-- wrong 

   }
}

我想在距离方法的 p1 和 p2 之后放置 3 和 4,但是我遇到了一个错误,如果我想这样做,我必须将整数放入其中,所以我的问题是我必须在调用中放入什么这个方法以便我可以运行它,即我必须为这个对象放置什么? “Space2D p1”? point2D.distance (???)

提前感谢您的帮助和解释,希望您能帮助我理解这一点。

【问题讨论】:

  • 欢迎来到 Stack Overflow。你想要distance(3, 4),所以传递几个整数会返回与distance(new Point2D(3,0), new Point2D(4,0)) 相同的值?

标签: java inheritance methods call point


【解决方案1】:
public double distance(Space2D p1, Space2D p2) {
...

这意味着当您调用distance 时,您必须传入两个Space2D 类型的对象。

point2D.distance(3,4) <-- wrong

你试图用两个整数调用它,这就是你得到错误的原因。点有一个 x 和 y 坐标,如果域是 R2,那么询问 3 和 4 之间的距离是什么意思。

你可能想要的是类似的东西

int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));

【讨论】:

    【解决方案2】:

    那是因为您将整数作为不允许作为参数的参数。距离函数取距离(Space2D p1, Space2D p2) Space2D 对象。

    你可以这样使用:

    在 Space2D 类中:

    public class Space2D {
    
        private int x;
        private int y;
    
        public Space2D(int x, int y) {
            this.x = x;
            this.y = y;
        }
        //several other methods etc.
    
        //for example I will take this method
    
        public static double distance(Space2D p1, Space2D p2) {
            double dx = p1.x - p2.x;
            double dy = p1.y - p2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }
    }
    

    在 SpaceTest 类中:

    public class SpaceTest extends Space3D {
        public static void main(String[] args) {
            Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 2011-10-17
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 2023-04-09
      • 2012-05-11
      相关资源
      最近更新 更多