首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java子类中添加两个变量作为一个变量传递给超类?

如何在java子类中添加两个变量作为一个变量传递给超类?
EN

Stack Overflow用户
提问于 2014-07-13 19:48:37
回答 2查看 834关注 0票数 1

我只是在学习Java,我有一个问题。我不确定我是否使用了正确的术语,所以如果需要的话请纠正我。我很好奇是否有更好的方法来增加前爪和后爪,把它们传递给动物类。这样做是可行的,但我在寻找我想要做的事情时遇到了困难,这使得我很难弄清楚我是否做错了。这是我正在工作的子类。

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2014-07-13 19:53:44

在调用超类构造函数之前,您不能访问字段--基本上,任何构造函数所做的第一件事就是调用超类构造函数。唯一要做的事是计算参数,以调用超类构造器--在您的例子中,这涉及到fCbC之和。

基本上,假设您需要Animal来得到frontClawsbackClaws之和,这看起来是一个合理的实现。

票数 0
EN

Stack Overflow用户

发布于 2014-07-13 19:59:59

1.

代码语言:javascript
复制
super (name, fC + bC); // This passes the name and the sum 
                           // of the claws to the Animal's constructor

是构造函数的第一行(必须如此),因为其中的第1条指令总是对超类构造函数的调用。

这将引发错误:

代码语言:javascript
复制
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 constructor

2.

代码语言:javascript
复制
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方法来选择它们的初始化。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24726536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档