我现在正在学习java。我有一个关于继承的问题。 我知道您可以使用以下方法继承父类的变量:
public class ChildClass extends ParentClass{
}
但是,我想做一些事情,比如从 ParentClass 的实例继承变量和分配给它们的值。示例:我有一个动物类和一个从动物扩展而来的狗类。动物类有:
private int number_of_legs;
private int number_of_eyes;
此时我创建了动物类的一个新实例:
Animal first_animal = new Animal(4,2);
/*where 4 and 2 are the number of legs and eyes which
*i attribute through a constructor present in Animal.
*/
现在我想创建 Dog 类的一个新实例,它继承了我刚刚创建的 Animal 类实例 (first_animal) 的值。
Dog first_dog = new ??? // i tried with ...new first_animal.Dog but it didn't work.
有人可以帮助我吗?感谢您抽出时间。
最佳答案
这样就可以了:
Dog dog = new Dog(4, 2);
您不能将子类的实例创建为父类(super class)的实例。您可以说所有 Dog
都是 Animal
,但并不是所有 Animal
都是 Dog
。
请注意,上面的语句意味着:
//valid and accepted because one kind of instance of animal is a dog
Animal dog = new Dog(4, 2);
//invalid and throws a compiler error because one kind of instance of a Dog cannot be any animal
Dog anotherDog = new Animal(4, 2);
<小时/>
new Animal.Dog
在这里是错误的,因为这意味着您在 Animal
类中有一个 static class Dog
。 new first_animal.Dog
在这里是错误的,因为这意味着您在 Animal
类中有一个内部类 Dog
。这些是您尚不应该讨论的不同主题。
关于java - 类继承的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084286/