Advertisement
defineSN

simple demo@polymorphism,inheritance,overriding,overloading

Jan 12th, 2013
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. /*
  2. a basic example of polymorphism,inheritance, overloading and overriding
  3. */
  4. import java.util.Scanner;
  5.  
  6. class Doctor{
  7.     boolean worksAtHospital;
  8.    
  9.     public void treatPatient(){
  10.         System.out.print("doctor\n he is now");
  11.         System.out.println(" gonna give you medicine :) ");
  12.     }
  13. }
  14.  
  15. class surgeon extends Doctor{
  16.     public void treatPatient(){ // overriding
  17.         System.out.print("surgeon\n he is now");
  18.         System.out.println(" doing operation!");
  19.     }
  20. }
  21.  
  22. class familyDoctor extends Doctor{
  23.     boolean makesHouseCalls;
  24.    
  25.     public void treatPatient(){ // overriding
  26.         System.out.print("family doctor\n he is now");
  27.         System.out.println(" giving advice..");
  28.     }
  29. }
  30.  
  31. class goToDoctor{
  32.     public void treatPatient(Doctor d){ // d is an object of type Doctor. d can also be a subclass of Doctor
  33.                                         //this is overloading (note: overloading has nothing to do with polymorphism or inheritance by itself)
  34.         d.treatPatient();
  35.     }
  36. }
  37.  
  38. class imUnwell{
  39.    
  40.     public static void main(String[] args){
  41.         Scanner input=new Scanner(System.in);
  42.         int whichDoctor;
  43.        
  44.         System.out.println(" who do you want to treat you?\n 1.Doctor?\n 2.Surgeon?\n 3.familyDoctor?");
  45.         whichDoctor=input.nextInt();
  46.        
  47.         System.out.print("option entered: " + whichDoctor + ">");
  48.         goToDoctor x = new goToDoctor();
  49.        
  50.         Doctor doc = new Doctor();
  51.         Doctor sur = new surgeon(); // polymorphism : doctor is superclass, surgeon is subclass
  52.         Doctor fam = new familyDoctor(); // polymorphism : doctor is superclass, family doctor is subclass
  53.        
  54.         if(whichDoctor==1)
  55.         x.treatPatient(doc); // passing object as argument
  56.         else if(whichDoctor==2)
  57.         x.treatPatient(sur);
  58.         else if(whichDoctor==3)
  59.         x.treatPatient(fam);
  60.        
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement