This section takes care of Casting(DownCasting and UpperCasting) Downcast: Casting down the inheritance tree to a more specific class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AnimalTest { | |
public static void main(String ...x) { | |
Animal a = new Animal(); | |
Dog d = (Dog)a; // downcasting | |
a.playDead(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
No comments:
Post a Comment