Java中的超类和子类 [英] Superclass and Subclass in Java
问题描述
对你来说,这可能很简单,但我不知道有什么区别.我只是想知道这两个代码之间的区别.假设我有一些代码,如下所述.
For you, this might be very simple but I have no idea what the difference is.I just want to know the difference between these two codes. Suppose I have some codes as described below.
第一个类是Animal,它将成为超类
The first class is Animal which will be the Superclass
public class Animal {
private String name;
private int weight;
private String sound;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setWeight(int weight){
if(weight > 0){
this.weight = weight;
} else {
System.out.println("Weight must be bigger than 0");
}
}
public int getWeight(){
return weight;
}
public void setSound(String sound){
this.sound = sound;
}
public String getSound(){
return sound;
}
}
第二个类是 Dog ,它扩展了类 Animal
The second class is Dog which extends the class Animal
public class Dog extends Animal {
public void digHole(){
System.out.println("Dig a hole");
}
public Dog(){
super();
setSound("bark");
}
}
最后一个类是WorkWithAnimals,它将打印输出
The last class is the WorkWithAnimals which will print the output
public class WorkWithAnimals {
public static void main(String args[]){
Dog fido = new Dog();
fido.setName("Dadu");
System.out.println(fido.getName());
fido.digHole();
fido.setWeight(-1);
}
}
我的问题是,Animal fido = new Dog() 和 Dog fido = new Dog() 有什么区别?
My question is, what is the difference between Animal fido = new Dog() and Dog fido = new Dog() ?
既然Dog已经继承了Animal,为什么还要写Animal fido = new Dog()这样的代码?
Since Dog already extends Animal, why do we have to write the code like Animal fido = new Dog() ?
它们都打印出相同的结果,不是吗?
Both of them print the same result, don't they?
推荐答案
Animal"类将不包含 digHole,所以你应该得到一个编译时错误;因此:
The class "Animal" will not include digHole, so you should get a compile time error; thus:
Animal fido = new Dog();
fido.dighole(); //<--compile time error
然而,
Dog fido = new Dog();
fido.dighole();
会好的.
这篇关于Java中的超类和子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!