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.
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;
}
}
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");
}
}
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);
}
}
My question is, what is the difference between Animal fido = new Dog() and Dog 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?