2013-07-03 46 views
0

OOP初学者在这里...我有一个名为Rectangle的超类,它有一个接受int高度和int宽度作为参数的构造函数。我的任务是创建一个改进的Rectangle子类,其中还包含一个不需要参数的构造函数。需要无参数的构造函数为子类,但超类没有它

那么,我该怎么做,而不会弄乱超类?

public class BetterRectangle extends Rectangle 
{ 
    public BetterRectangle(int height, int width) 
    { 
     super(height,width); 
    } 

    public BetterRectangle() 
    { 
      width = 50; 
      height = 50; 
    } 
} 

这给了我“隐式超级构造函数是未定义”。显然我需要调用超类的构造函数。但是用什么?只是随机值,后来被覆盖?

+0

另一个问题是您没有宽度,高度的实例变量,因此分配也失败。 – kosa

+2

@Nambari它们可以在'Rectangle'中定义为非'private'成员。 – GriffeyDog

+0

@GriffeyDog:如果是这样的话,我认为使用构造函数重新设置值是多余的权利? – kosa

回答

6

试试这个:

public BetterRectangle() 
{ 
     super(50, 50); // Call the superclass constructor with 2 arguments 
} 

或者:

public BetterRectangle() 
{ 
     this(50, 50); // call the constructor with 2 arguments of BetterRectangle class. 
} 

你不能使用你的代码在构造函数中的第一行是在调用super()或()这个。如果没有对super()或this()的调用,那么调用是隐含的。您的代码相当于:

public BetterRectangle() 
{ 
     super(); // Compile error: Call superclass constructor without arguments, and there is no such constructor in your superclass. 
     width = 50; 
     height = 50; 
} 
+0

当然,但如果我不想要矩形为50x50,但有一些用户定义的值? –

+1

这不就是其他ctor的用途吗? – duffymo

+0

如果您不传递参数,用户如何传递它们的值?在无参数构造函数中,您需要提供默认值。 – eternay

相关问题