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

问题描述:

是否有可能使用父类来为超类中的共享方法存储常用值,但仍然使用子类的单独构造函数(即存储任意值k从不同子类的两个构造函数的参数转换为超类,但仍然调用两个子类中的单独构造函数和不同的构造函数)?调用super来存储值,但使用子类的构造函数

在子类:

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来存储值之后,有可能调用构造函数的其余部分?

+1

我想你应该做一些真实的例子,因为从描述中不清楚你想做什么。 – Jack

+0

@jack补充例子,谢谢。 – hliu

这是一个常见的用例的基类的保护的构造:

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); 
     ... 
    } 
    ... 
} 
+0

在超级类的构造函数中,final和protected做了什么?谢谢! – hliu

+0

@hliu'protected'意味着你不能直接使用这个构造函数来构造'Base',即'void main(String [] args){Base b = new Base(1); }'不会编译。 “val”声明中的“final”使该字段成为只读字段。 – dasblinkenlight

方法superPicture是公众超类和被继承为使用成延伸类。

你可以简单地调用它。

如果你重写它,你也可以通过super.superPicture(width,height)来访问它;