I was trying to learn Java from Tutorials Point. So, may be this question would be so basic. But I am really stuck here. And I don't know what to google to get it resolved.
Please have a look at this program.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal();
Animal b = new Dog();
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
Please have a look at the object creation.
Animal a = new Animal();
Animal b = new Dog();
What is the difference between these two? I am familiar with the first one. Could someone explain in simple terms what happens when an object is defined in the second way?
Animal a = new Animal();
--> creates an instance ofAnimal
referenced as anAnimal
. OnlyAnimal
methods will be available to invoke froma
.Animal b = new Dog();
--> sinceDog
extendsAnimal
, creates an instance ofDog
referenced as anAnimal
. OnlyAnimal
methods (i.e. no methods pertaining only toDog
) will be available to invoke fromb
, but the virtual method invocation mechanism will resolve method invocation toDog
's implementations at runtime, when overridingAnimal
's.Note
Object
methods (equals
,hashCode
,wait
overloads,notify
,notifyAll
,toString
andgetClass
) are available to all objects.Fully commented example
Dog
class inherits fromAnimal
class.In the example above, the first creates and
Animal
object while the second creates aDog
object. But because theDog
class inherits from theAnimal
class, themove()
function inDog
overrides themove()
function inAnimal
(since they are they have the same function prototype).Thus, when you run the
b.move()
, you run theDog
'smove()
function instead.