+ 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

29th Nov 2017, 3:35 PM
Laxman Rathod
Laxman Rathod - avatar
6 Respostas
+ 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
29th Nov 2017, 3:55 PM
David Akhihiero
David Akhihiero - avatar
+ 10
@Laxman, the animal object will have the eatFood() method
29th Nov 2017, 4:01 PM
David Akhihiero
David Akhihiero - avatar
+ 10
@Laxman, my bad...The animal object will only have the makeSound() method of the dog class, its own is overrided
29th Nov 2017, 4:11 PM
David Akhihiero
David Akhihiero - avatar
+ 7
you don't have loss of data because class Dog have all features off class animal and some extra features
29th Nov 2017, 3:56 PM
Vukan
Vukan - avatar
+ 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
29th Nov 2017, 3:59 PM
Laxman Rathod
Laxman Rathod - avatar
+ 1
@Yerucham The Animal object will not have the eatFood() method it will give error :(
29th Nov 2017, 4:04 PM
Laxman Rathod
Laxman Rathod - avatar