所以我在一些与我合作的代码中遇到了一些障碍。基本上我有以下三个代码:
抽象类:
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();
}
}
答案 0 :(得分:2)
考虑以下抽象类的情况并扩展实现。 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有一个允许调用者指定值的构造函数。
注意:由于父抽象类中没有默认(或无参数)构造函数,因此必须指定子类中使用的构造函数。
抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。
答案 1 :(得分:1)
如果在超类中定义了显式构造函数,并且没有定义参数的构造函数,则子类应显式调用超类构造函数。
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
或者,如果您不希望调用带有参数的超类构造函数,则需要在超类中添加不带参数的构造函数。
public abstract class TestParent {
int size;
public TestParent(){
}
public TestParent(int i){
size = i;
}
}
答案 2 :(得分:1)
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);
}
}
答案 3 :(得分:1)
使用super
调用父(TestParent.TestParent(int)
)构造函数:
public class TestChild extends TestParent{
public TestChild(int i) {
super(i);
}
//...
}
或者如果你想使用一些常数:
public TestChild() {
super(42);
}
请注意,Java中没有抽象构造函数。基本上TestParent
中只有一个构造函数必须在调用TestChild
构造函数之前调用。
另请注意,super()
必须始终是第一个声明。
答案 4 :(得分:0)
您的代码不会编译,因为您的基类没有默认构造函数。您需要在基类中提供它,或者您需要在派生类中提供参数化构造函数并调用super。
答案 5 :(得分:0)
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;
}
}
对于此解决方案,尺寸必须受到保护或公开。