Advertisement
brandblox

DMD

Dec 15th, 2023
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. class Phone {
  2.     void showTime() {
  3.         System.out.println("Phone: Showing time");
  4.     }
  5.  
  6.     void on() {
  7.         System.out.println("Phone: Turning on");
  8.     }
  9. }
  10.  
  11. class SmartPhone extends Phone {
  12.     void music() {
  13.         System.out.println("SmartPhone: Playing music");
  14.     }
  15.  
  16.     @Override
  17.     void on() {
  18.         System.out.println("SmartPhone: Turning on");
  19.     }
  20. }
  21.  
  22. public class DynamicDemo {
  23.     public static void main(String[] args) {
  24.         // Dynamic method dispatch
  25.         Phone phone1 = new Phone();
  26.         Phone phone2 = new SmartPhone();
  27.  
  28.         phone1.showTime(); // Calls showTime from Phone class
  29.         phone1.on();       // Calls on from Phone class
  30.  
  31.         phone2.showTime(); // Calls showTime from Phone class
  32.         phone2.on();       // Calls on from SmartPhone class
  33.  
  34.         // Additional method specific to SmartPhone
  35.         // phone2.music(); // This line will cause a compilation error
  36.  
  37.         // To use the music method, you need to declare the object as SmartPhone
  38.         SmartPhone smartPhone = new SmartPhone();
  39.         smartPhone.music(); // Calls music from SmartPhone class
  40.     }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement