扩展抽象构造函数



所以我在处理的一些代码中遇到了一些障碍。从本质上讲,我有以下三条代码:

抽象类:

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进行硬编码。具体类TimesWhat有一个构造函数,允许调用者指定值。

注意:由于父抽象类中没有默认(或没有arg)构造函数,因此必须指定子类中使用的构造函数。

抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。

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中没有抽象构造函数这样的东西。本质上,TestParent中只有一个构造函数,在调用TestChild构造函数之前必须调用它。

还要注意,super()必须始终是第一个语句。

当您在超类中定义了显式构造函数,并且没有定义没有参数的构造函数时,您的子类应该显式调用超类构造函数。

public class TestChild extends TestParent{
        TestChild ()
        {
            super(5);
        }
    }

或者,如果您不想用参数调用超类构造函数,则需要在超类中添加不带参数的构造函数。

public abstract class TestParent {
    int size;
    public TestParent(){
    }
    public TestParent(int i){
        size = i;
    }
}

您的代码不会编译,因为您的基类没有默认构造函数。要么需要在基类中提供它,要么需要在派生类中提供参数化构造函数并调用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;
             }
}

对于此解决方案,大小必须是受保护的或公共的。

最新更新