Reputation: 1
here what is the purpose of giving animal reference to dog object ..we can directly access the method by creating object to dog class please clarify
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}
Upvotes: 0
Views: 71
Reputation: 871
class Dog extends Animal
What the code snippet does
It makes the Animal class as Dog's parent. Since Dog class inherited Animal class, Animal class becomes the parent of Dog class.
In creating objects
If you want to use only the properties of Dog, then Dog as the object's type is enough.
Dog b = new Dog();
If you want to use the properties of Animal and Dog, then use Animal as object's type.
Animal b = new Dog();
That's why Animal object can be used as a reference to a Dog object.
Upvotes: 1
Reputation: 397
You see that the class Animal is being parent class to the class Dog.
We use this concept in the case that to share the properties of Base class to Derived class (Animal attributes applying to Dog)
So an attribute of move has been a method in Base class that could be derived in class Dog, and using its properties.
We can use or build over it - Method Overloading.
@Override annotate can be used - but optional
Creating the Object for the Derived class (which get the functionality of Base class and its own class) of type Base class.
So basically it (Base class) works like core and (Derived class) works like Implementation.
Hope it helps.
Upvotes: 0