What is Polymorphism, Abstraction and Encapsulation?

Polymorphism

Polymorphism is a capability of an object to take on many forms. Which means when an object has more than one “is-a” relationship, it is considered as polymorphic.

Code example:

public class HospitalPatient {

void status() {

System.out.println(“feels weak”);

}

}

public class FluPatient extends HospitalPatient {

void status() {

System.out.println(“coughing with fever”);

}

}

Abstraction

Abstraction is providing only essential methods to the user while hiding other details. It reduces the complexity of the code.

To implement abstraction, set the essential methods of the class as public and make the other methods as private. The public methods will be available to the user, while the private methods will stay inaccessible.

Code example:

public class HospitalPatient {

public int patientId;

public String name;

private double weight;

private List symptoms;

}

Encapsulation

Encapsulation is making the fields in a class private and providing access to the fields via public methods. This prevents your code from being modified and provides flexibility and extensibility.

The only way to gain access to the data is through accessors (getters and setters).

Code example:

public class HospitalPatient {

private String name;

public String getName () {

return name;

}

Public void setName (String name) {

name = patientName;

}

}