Inheritance explained with real life example

public class Doctor {
private String name;
private String specialization;
....

public void treatPatient(){
// treating patients
}
// more methods to follow
....

Specialized Doctors

  1. An Ortho is-a Doctor and inherit the attributes and methods from Doctor class.
  2. Doctor class does not even know that it is being extended by other class. In fact it does not even know the existence of Orthod/Padietric class. There is no reason for it to know.
  3. An Ortho can only inherit attributes and method from one class. In Java, a class can extend only one class. More on this a bit later…
  4. Both Ortho and Padietric are extending from Doctor class and share the is-a relationship with Doctor, but there is no relationship between them. Ortho is not a Padietric and vice versa.
public class Orthopedic extends Doctor {    //inherit instance attributes and methods from Doctor class
// more method to follow
...
}
public class Pediatric extends Doctor {
// inherit instance attributes and methods from Doctor class
//more method to follow
...
}
public class Orthopedic extends Doctor {
// specialized methods added
public void conductXRay(){}
public void conductCTScan(){}
}
public class Pediatric extends Doctor{
//specialized method for Pediatric
public void examineKids(){}
}
public class Client {
public static void main(String args[]){
Doctor doctor = new Doctor(); //valid
Orthopedic ortho = new Orthopedic(); //valid
Doctor orthoDoc = new Orthopedic();// valid
Doctor peditricDoc = new Pediatric(); // valid
// not valid since peditaric is not a Orthopedic
Orthopedic orthoDoctor = new Pediatric();
// not valid since Doctor is not Orthopedic
Orthopedic doctor1 = new Doctor();
}
}
Orthopedic orthoDoctor = new Pediatic();
Orthopedic doctor1 = new Doctor();

“instanceof“ operator for rescue.

Doctor doctor = new Doctor();
Orthopedic ortho = new Orthopedic();
System.out.println(doctor instanceof Orthopedic); // prints false
System.out.println(ortho instanceof Orthopedic); //prints true
System.out.println(orthoDoc instanceof Pediatric); //prints false
System.out.println(ortho instanceof Doctor); //prints true

Multilevel Inheritance

public class KneeSurgeon extends Orthopedic {
public void kneeSurgery(){}
}
  1. ArrayList extends AbstractList.
  2. Wrapper classes like Integer, Double extends Number class.
  3. SimpleDateFormat extends DateFormat class.
  4. All classes in Java extends Object class implicitly.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store