[英]Extending an abstract constructor?
因此,我在使用的一些代码中遇到了一些麻烦。 本质上,我有以下三个花絮:
抽象类:
public abstract class TestParent {
int size;
public TestParent(int i){
size = i;
}
}
儿童班:
public class TestChild extends TestParent{
public void mult(){
System.out.println(this.size * 5);
}
}
实现方式:
public class TestTest {
public static void main(String args[]) {
TestChild Test = new TestChild(2);
Test.mult();
}
}
考虑以下抽象类的情况并扩展实现。 https://stackoverflow.com/a/260755/1071979
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return muliplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
超类Product是抽象的,并且具有构造函数。 具体的类TimesTwo具有一个默认构造函数,该构造函数仅对值2进行硬编码。具体的TimesTime类具有允许调用者指定该值的构造函数。
注意:由于父抽象类中没有默认(或无参数)构造函数,因此必须指定子类中使用的构造函数。
抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。
当您在超类中定义了显式构造函数而没有定义无参数的构造函数时,您的子类应显式调用超类构造函数。
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
或者,如果您不想使用参数调用超类构造函数,则需要在超类中添加不带参数的构造函数。
public abstract class TestParent {
int size;
public TestParent(){
}
public TestParent(int i){
size = i;
}
}
public class TestChild extends TestParent{
public TestChild(int i){
super(i); // Call to the parent's constructor.
}
public void mult(){
System.out.println(super.size * 5);
}
}
使用super
调用父( TestParent.TestParent(int)
)构造函数:
public class TestChild extends TestParent{
public TestChild(int i) {
super(i);
}
//...
}
或者如果您想使用一些常量:
public TestChild() {
super(42);
}
请注意,Java中没有诸如抽象构造函数之类的东西。 本质上,在调用TestChild
构造函数之前,必须在TestParent
只有一个构造函数。
还要注意, super()
必须始终是第一条语句。
您的代码不会编译,因为您的基类没有默认的构造函数。 您需要在基类中提供它,或者需要在派生类中提供参数化的构造函数并调用super。
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i * 2);
}
}
此代码将使用i的两倍。 这是最重要的,尽管我不确定您要问什么。
其他解决方案:
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i);
this.size = 105;
}
}
对于此解决方案,必须保护大小或公共大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.