我只是在学习Java,我有一个问题。我不确定我是否使用了正确的术语,所以如果需要的话请纠正我。我很好奇是否有更好的方法来增加前爪和后爪,把它们传递给动物类。这样做是可行的,但我在寻找我想要做的事情时遇到了困难,这使得我很难弄清楚我是否做错了。这是我正在工作的子类。
public class Bear extends Animal // This is a Bear class, it is a subclass of Animal.
{
private int frontClaws; // This is an instance variable for front claws.
private int backClaws; // This is an instance variable for back claws.
public Bear (String name, int fC, int bC) // This is the Bear constructor.
{
super (name, fC + bC); // This passes the name and the sum
// of the claws to the Animal's constructor
frontClaws = fC; // not sure why this has to be done,
// and frontClaws + backClaws can't be used directly. Because they are private?
backClaws = bC; // Same as confusion as above.
}
public void print() // This calls the print method.
{
super.print(); // This calls the print method from
// Animal and prints the args from Animal
// as well as the args from Bear.
System.out.println("- " + frontClaws + " Front Claws, and " + backClaws + " Back Claws.");
}
}提前感谢!
tc
发布于 2014-07-13 19:53:44
在调用超类构造函数之前,您不能访问字段--基本上,任何构造函数所做的第一件事就是调用超类构造函数。唯一要做的事是计算参数,以调用超类构造器--在您的例子中,这涉及到fC和bC之和。
基本上,假设您需要Animal来得到frontClaws和backClaws之和,这看起来是一个合理的实现。
发布于 2014-07-13 19:59:59
1.
super (name, fC + bC); // This passes the name and the sum
// of the claws to the Animal's constructor是构造函数的第一行(必须如此),因为其中的第1条指令总是对超类构造函数的调用。
这将引发错误:
public Bear (String name, int fC, int bC) // This is the Bear constructor.
{
frontClaws = fC;
backClaws = bC;
int totalClaws = fC + bC;
super (name, totalClaws );
}
error: call to super must be first statement in constructor2.
frontClaws = fC; // not sure why this has to be done,
// and frontClaws + backClaws can't be used directly. Because they are private?
backClaws = bC; // Same as confusion as above.因为他们是私人的?
您基本上是从构造函数中初始化它们,以便将它们传递给超类的构造函数。如果不是这样的话,那么您可以通过setter方法来选择它们的初始化。
https://stackoverflow.com/questions/24726536
复制相似问题