繁体   English   中英

调用super来存储值,但使用子类构造函数

[英]Calling super to store values, but using subclass constructor

是否可以使用父类以便为父类中的共享方法存储公共值,但仍为子类使用单独的构造函数(即,将来自不同子类的两个构造函数的参数中的任意值k存储到父类中? ,但仍要调用两个子类中的各个构造函数)。

例如

在子类中:

public pictureImpl(Picture source, int x, int y, int height, int width) { 
    super(height, width);
    "rest of constructor using all parameters"
}

在超类中:

public superPicture(int height, int width) {
   heightValue = height;
   widthValue = width;
}

在这里,仍然可以在子类的括号中使用该部分(即,即使在使用super存储值之后,也可以调用构造函数的其余部分吗?

这是基类的受保护构造函数的常见用例:

class Base {
    private final int val;
    protected Base(int val) {
        this.val = val;
    }
    public int getVal() {
        return val;
    }
}
class Derived1 extends Base {
    public Derived1(String name, int val) {
        super(val);
        ...
    }
    ...
}
class Derived2 extends Base {
    public Derived2(int val, Date timestamp) {
        super(val);
        ...
    }
    ...
}

方法superPicture在超类上公开,并且继承使用以扩展类。

您可以简单地调用它。

如果覆盖它,也可以使用super.superPicture(width,height);对其进行访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM