+ 2
Type casting not clear
Class Animal{ public void makeSound(){ .. } } class Dog extends Animal{ public void makeSound(){ .. } public void eatFood(){ .. } } Now letâs make an analogy with data types Animal=> int // since it contains only one method makeSound() thus small size Dog => double // since it contains two methods makeSound() and eatFood() thus big size Then why is Animal a = new Dog() // upcasting implicit shouldnât it be explicit since there is loss of data
6 Answers
+ 11
What loss of data?
What is happening is that an Animal object is created that will have /*all of dog methods,*/ so yes it is upcasting
Edit: *only the dog methods that override Animal methods
+ 10
@Laxman, the animal object will have the eatFood() method
+ 10
@Laxman, my bad...The animal object will only have the makeSound() method of the dog class, its own is overrided
+ 7
you don't have loss of data because class Dog have all features off class animal and some extra features
+ 2
Since a is of type Animal and new Dog() will create an object of type Dog and assign to a
So isnât there a loss of data as a can hold only one method i.e makeSound()
Sorry I may be asking a very basic question but I am not convinced
+ 1
@Yerucham The Animal object will not have the eatFood() method it will give error :(