Tuesday, June 19, 2012

Reference Variable Casting


This section takes care of Casting(DownCasting and UpperCasting) Downcast: Casting down the inheritance tree to a more specific class
class Animal {
void makeNoise() {
System.out.println("Generic noise");
}
}
class Dog extends Animal {
void makeNoise() {
System.out.println("Bark");
}
void playDead() {
System.out.println("Playing");
}
}
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Dog();
Dog d = (Dog)a; // downcast
a.playDead();
}
}
view raw gistfile1.java hosted with ❤ by GitHub
The compiler trusts in us even if you're trying to cast object that does not refer a dog.
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Animal();
Dog d = (Dog)a; // downcasting
a.playDead();
}
}
view raw gistfile1.java hosted with ❤ by GitHub
The code above compiles well but you'll get an exception(java.lang.ClassCastException) at runtime, it occurrs because the compiler only verifies an inheritance tree, in this case Dog is a subtype of Animal. !Important Watch out, the code above compiles the exception is throwns at runtime. Upcasting: Unlike downcasting you don't have to type anything like the previous example Dog d = (Dog)a, the upcasting is implicitly, in other words you're restricting the number of methods that you can invoke.
class Computer {
void turnOn() {
System.out.println("Turning on Computer");
}
}
class MacBook extends Computer {
void turnOn() {
System.out.println("Turning on MacBook");
}
void openMacX() {
System.out.println("Openning a MacX");
}
}
public class ComputerTest {
public static void main(String x[]) {
MacBook m = new MacBook();
Computer c = m; // upcasting - implicitly
Computer c = (Computer)m; //upcasting - explicitly
}
}
view raw gistfile1.java hosted with ❤ by GitHub
Finally the casting can be at one line.
public class AnimalTest {
public static void main(String ...x) {
Animal a = new Dog();
Dog d = (Dog)a; // downcasting
a.playDead();
((Dog)a).playDead(); // at one line
}
}
view raw gistfile1.java hosted with ❤ by GitHub

No comments: