+ 1
Declaring variables of a superclass
What is the difference between declaring a variable of the type of a superclass and declaring it of the type of a subclass? Example: Class Animal { // Do something } Class Cat extends Animal { // Do something } Class Dog extends Animal { // Do something } It is the same this: Animal a = new Dog (); Animal b = new Cat (); That this:? Dog a = new Dog (); Cat b = new Cat ();
2 odpowiedzi
+ 1
The difference is how you can acces them.
When you declare the Cat and Dog both as Animals, you could put them in the same array, iterate over them and execute their speak()-method
Example:
Animal a1 = new Cat(); Animal a2 = new Dog();
Animal[] animals= {a1,a2};
for(Animal animal : animals){
animal.speak();
}
That's useful when you wish to store a lot of different object with the same superclass in a list.
However, if Dog or Cat has a method that is not declared in Animal, you cannot access this method when the Dog/Cat is declared as an Animal object.
Example:
Animal a3 = new Dog();
a3.dig() // does not compile
this WOULD work in the following way:
(Dog)a3.dig(); //compiles
Therefor
Animal a4 = new Dog();
Dog d1 = new Dog();
System.out.println(a4.equals(d1));
prints: false.
Because they are not the same type of object.
0
The difference when downcasting like this (using the common superclass object when declaring and instantiating the object) is that only the values and method that are common to the superclass are available.
take in account the following code:
public class Program
{
public static void main(String[] args) {
Animal dog1 = new Dog();
Animal cat1 = new Cat();
dog1.speak();
cat1.speak();
dog1.jump();
cat1.jump();
// dog1.dig();
// cat1.scratch();
}
}
public class Animal {
int legs = 4;
public void speak() {
System.out.println("Animal says Hello");
}
public void jump() {
System.out.println("Animal Jumping...");
}
}
public class Dog extends Animal {
public void speak() {
System.out.println("Dog Barking...");
}
public void dig() {
System.out.println("Digging...");
}
}
public class Cat extends Animal {
public void speak() {
System.out.println("Cat Meowing...");
}
public void scratch() {
System.out.println("Cat Scratching...");
}
}
When this is ran and the dog1.speak() method is called it calls the overridden speak() method from the Dog class as expected. When the dog1.jump() method is called it runs the method from the super class, again as expected. Now uncomment the dog1.dig() method which the Animal class doesn't have and the program won't compile.