Aim:
Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation,
Inheritance, Polymorphism and Abstraction]
Source Code:
[Link]
/* Encapsulation:
The fields of the class are private and accessed through
getter and setter methods.*/
class Person {
// private fields
private String name;
private int age;
// constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
/* Abstraction:
The displayInfo() method provides a simple interface to
interact with the object.*/
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
/* Inheritance:
Employee is a subclass of Person, inheriting its properties
and methods.*/
class Employee extends Person {
// private field
private double salary;
// constructor
public Employee(String name, int age, double salary) {
super(name, age);
[Link] = salary;
}
// getter and setter methods
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
[Link] = salary;
}
/* Polymorphism:
Overriding the displayInfo() method to provide a specific
implementation for Employee.*/
@Override
public void displayInfo() {
[Link]();
[Link]("Salary: " + salary);
}
}
public class OopPrinciplesDemo {
public static void main(String[] args) {
// Demonstrating encapsulation and abstraction
Person person = new Person("Madhu", 30);
[Link]("Person Info:");
[Link]();
[Link]("====================");
// Demonstrating inheritance and polymorphism
Employee employee = new Employee("Naveen", 26, 50000);
[Link]("Employee Info:");
[Link]();
}
}
Output: