+ 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?
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 ());
}
}
+ 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();
0
Good example.
0
Is Sidd right?