英文:
Java parent class using child class attributes
问题
public class Animal {
String name;
String species;
public void introduction() {
System.out.println("Hi, my name is " + name + ", I am a " + species);
}
}
public class Dog extends Animal {
public Dog() {
species = "dog";
}
}
// You can create similar classes like Cat, Bird, etc., with their unique species attribute
public class Cat extends Animal {
public Cat() {
species = "cat";
}
}
public class Bird extends Animal {
public Bird() {
species = "bird";
}
}
英文:
public animal{
String name;
String species;
public introduction(){
System.out.println("Hi, my name is" + name +", i am a " + species);
}
}
public dog extends animal{
String species = "dog";
}
I am wondering if i were to build more child classes like cat, bird etc, with with their unique species
variable. If there a way whereby I can make them self-introduce different according to their species?
I understand that I am asking a parent class to access a child-class attribute, which seems to defeat the purpose of inheritance in the first place, but I am not sure what is a more elegant way of doing this.
答案1
得分: 1
根据您的animal.class
,您似乎已经定义了一个名为name
和species
的公共成员变量。这显然是子类cat.class
和dog.class
的一部分。
您的父类存在语法错误,函数应该返回void
,像这样:
public void introduction(){
System.out.println("Hi, my name is" + name + ", i am a " + species);
}
您的子类将如下所示:
class Cat extends Animal{
public Cat(){
super.name = "tom";
super.species = "cat";
}
}
class Mouse extends Animal{
public Mouse(){
super.name = "jerry"; //简单地调用 name = "jerry" 即可,因为这是继承来的。
super.species = "mouse";
}
}
注意,我没有在子类级别使用成员变量,您可以这样调用它们:
Animal cat = new Cat();
Animal mouse = new Mouse();
cat.introduction(); // 输出 Hi, my name is tom...
mouse.introduction(); // 输出 Hi, my name is jerry ...
另外,按照编程准则,最好遵循驼峰命名法,例如(Animal 而不是 animal)。
英文:
Based on your animal.class
you already seem to have defined a public member variable name
and species
. This is obviously part of the child classes namely cat.class
and dog.class
Your parent class has syntax errors function should return void
like so:
public void introduction(){
System.out.println("Hi, my name is" + name +", i am a " + species);
}
Your child classes would look like this:
class Cat extends Animal{
public Cat(){
super.name = "tom"
super.species = "cat"
}
}
class Mouse extends Animal{
public Mouse(){
super.name = "jerry" //simply calling name = "jerry" will work as this is inherited.
super.species = "mouse"
}
}
Note that I haven't child level member variables, and you can call them like so:
Animal cat = new Cat();
Animal mouse = new Mouse();
cat.introduction(); // prints Hi, my name is tom...
mouse.introduction(); //prints Hi, my name is jerry ...
Also, it is a good practise to follow Programming guidelines as CamelCasing your classes. eg(Animal instead of animal)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论