【问题标题】:return value of a function in super constructor超级构造函数中函数的返回值
【发布时间】:2016-10-21 17:56:25
【问题描述】:

我必须返回一个函数的值作为 super() 的参数 特别是我有一个类 Polygon(Point[] vertex) 和一个类 Rectangle extends Polygon

Rectangle 类在其构造函数中接受两个参数,它们是两个 Point,代表 Rectangle 的两个随机顶点,有助于计算另外两个

关键是,当我创建构造函数 Rectangle(p1,p2) 时,我必须调用 super() 传递从 p1 和 p2 开始构建的顶点数组; 那么为什么我不应该调用一个函数来计算数组并​​将其传递给 super() 呢?

【问题讨论】:

  • 必须先调用超级构造函数,不能在它之前调用函数。你问的是这个吗?
  • 你需要在Rectangle中创建一个方法private static Point[] createVertices(Point p1, Point p2){...}。然后你可以调用super(createVertices(Point p1, Point p2)) 作为Rectangle 构造函数的第一行。
  • 谢谢!!!!它有效!

标签: java


【解决方案1】:

对超级构造函数的调用必须是方法中的第一次调用。这里最简单的解决方案是使用静态助手:

public class Rectangle extends Polygon {
    public Rectangle (int parameter) {
         super(myhelper(parameter));
    }
    private static Point[] myhelper(int parameter) {
        //Do work here!
        return points;
    }
}

如果您发现您的类只不过是复杂的构造函数,这可能表明您实际上并不需要子类。你通常可以实现这样的东西:

public static Polygon rectangleBuilder(int param) {
   //Do work here!
   return new Polygon(points);
}

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多