+ 2

Reason for CLASS casting?

The discussions below seem to focus of casting of data types, but did not mention the rationale for casting of classes. Like in the example, Animal a = new cat(); if I was meant to create an object of the superclass, I’d use Animal a = new Animal(); if I was meant to create an object of the subclass, cat (and ask it to make sound), I’d use Cat a = new Cat(); a.makeSound(); Then, what is the point of writing Animal a = new cat(); (upcasting) OR Animal a = new Animal(); ((cat).a).makeSound(); (downcasting)? I understand how casting works syntax-wise. I understand why do we cast datatypes. But I have no idea why we cast classes. Any real-life example or source-code based elaboration?

14th Aug 2016, 5:37 PM
Ka Ho Hui
Ka Ho Hui - avatar
4 Answers
+ 8
Well this is one of the OOP concept. Ex: class Car { public String getCompany(){ return null; } } class Corola extends Car { public String getCompany(){ return "Toyota"; } } class City extends Car { public String getCompany(){ return "Honda"; } } class Test { public static void main (String[] args){ Car c1 = new Corola (); Car c2 = new City (); show (c1); //Toyota show (c2); //Honda } // show method accepts all classes that extend Car public static void show (Car car){ System.out.println (car.getCompany ()); } }
14th Aug 2016, 7:02 PM
Tiger
Tiger - avatar
+ 1
nice answer but I want to add 1 more thing if class City has one more method public int getPrice(){ return 10; } then we can't call this method like this c2.getPrice(); because class Car doesn't has dis method here we have to use downcast ((City)c2).getPrice();
14th Nov 2016, 7:53 AM
Sidd
Sidd - avatar
0
Good example.
14th Aug 2016, 9:04 PM
WPimpong
WPimpong - avatar
0
Is Sidd right?
6th Dec 2016, 11:14 AM
Felipe Parra
Felipe Parra - avatar