Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Phone {
- void showTime() {
- System.out.println("Phone: Showing time");
- }
- void on() {
- System.out.println("Phone: Turning on");
- }
- }
- class SmartPhone extends Phone {
- void music() {
- System.out.println("SmartPhone: Playing music");
- }
- @Override
- void on() {
- System.out.println("SmartPhone: Turning on");
- }
- }
- public class DynamicDemo {
- public static void main(String[] args) {
- // Dynamic method dispatch
- Phone phone1 = new Phone();
- Phone phone2 = new SmartPhone();
- phone1.showTime(); // Calls showTime from Phone class
- phone1.on(); // Calls on from Phone class
- phone2.showTime(); // Calls showTime from Phone class
- phone2.on(); // Calls on from SmartPhone class
- // Additional method specific to SmartPhone
- // phone2.music(); // This line will cause a compilation error
- // To use the music method, you need to declare the object as SmartPhone
- SmartPhone smartPhone = new SmartPhone();
- smartPhone.music(); // Calls music from SmartPhone class
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement