gpt4 book ai didi

java - 如何在 java 子类中添加两个变量以作为一个变量传递给父类(super class)?

转载 作者:太空宇宙 更新时间:2023-11-04 14:43:13 25 4
gpt4 key购买 nike

我正在学习Java,我有一个问题。我不确定我使用的术语是否正确,因此如有必要,请纠正我。我很好奇是否有更好的方法来添加前爪和后爪以将它们传递给 Animal 类。这是按原样工作的,但我在搜索我想要做的事情时遇到了困难,这使得很难弄清楚我是否做错了。这是我正在使用的子类。

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

最佳答案

在调用父类(super class)构造函数之前,您无法访问字段 - 基本上,任何构造函数所做的第一件事就是调用父类(super class)构造函数。您要做的唯一一件事就是评估参数以调用该父类(super class)构造函数 - 在您的情况下,这涉及将 fCbC 相加。

基本上,假设您需要 Animal 来获得 frontClawsbackClaws 的总和,这看起来像合理实现。

关于java - 如何在 java 子类中添加两个变量以作为一个变量传递给父类(super class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com