Why is it useful to use a superclass as a reference while creating an object of subclass in Java? superclass obj = new subclass()
I have done a lot of research and all I can find is that in an Array you can declare the Array as type Superclass and then create objects like the above (superclass type referencing subclass object) and insert into the array. However I have tried to create subclass objects without a superclass reference and insert into an array and it works. I am not understanding why someone would ever create superclass obj = new subclass()
See code:
import java.util.*;
public class Pet
{
private String name;
private String type;
public Pet(String n, String t)
{
name = n;
type = t;
}
public String toString()
{
return name + " is a " + type;
}
public static void main(String[] args)
{
Pet[] animals = new Pet [5];
// This still works to insert into animals array of type Pet. Why?
Dog p1 = new Dog("Fido");
//According to various sources the above should not work but the following should
//Pet p1 = new Dog("Fido);
animals[0] = p1;
// This loop will work for all subclasses of Pet
for(Pet p : animals)
{
System.out.println(p);
}
}
}
class Dog extends Pet
{
public Dog(String n)
{
super(n, "dog");
}
}