Java 扩展抽象构造函数?
因此,我在使用的一些代码中遇到了一些障碍。基本上,我有以下三点代码: 抽象类:Java 扩展抽象构造函数?,java,constructor,abstract,Java,Constructor,Abstract,因此,我在使用的一些代码中遇到了一些障碍。基本上,我有以下三点代码: 抽象类: public abstract class TestParent { int size; public TestParent(int i){ size = i; } } 儿童班: public class TestChild extends TestParent{ public void mult(){ System.out.prin
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();
}
}
当您在超类中定义了显式构造函数,并且没有未定义参数的构造函数时,您的子类应该显式调用超类构造函数
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
或者,如果不想使用参数调用超类构造函数,则需要在超类中添加不带参数的构造函数
public abstract class TestParent {
int size;
public TestParent(){
}
public TestParent(int i){
size = i;
}
}
使用
super
调用parent(TestParent.TestParent(int)
)构造函数:
public class TestChild extends TestParent{
public TestChild(int i) {
super(i);
}
//...
}
或者,如果要使用某个常量:
public TestChild() {
super(42);
}
请注意,Java中没有抽象构造函数。本质上,TestParent
中只有一个构造函数,在调用TestChild
构造函数之前必须调用该构造函数
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
还要注意的是
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;
}
}
对于此解决方案,大小必须是受保护的或公共的 考虑以下抽象类的情况并扩展实现。 超类产品是抽象的,具有构造函数。具体类TimesTwo有一个默认构造函数,它只硬编码值2。具体类TimesWhat具有允许调用方指定值的构造函数 注意:由于父抽象类中没有默认(或无arg)构造函数,因此必须指定子类中使用的构造函数
抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。我错过了吗?我没有看到一个问题:)@jeff问题是:当你的超类没有使用默认的无参数构造函数时,它为什么不编译?实现者必须提供一个构造函数
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);
}
}