OOP Assignment: Inheritance and Polymorphism
📝 Objective:
To understand and explain the core principles of Object-Oriented Programming (OOP)
with a focus on Inheritance and Polymorphism, along with supporting concepts like
Encapsulation and Abstraction.
💡 Core OOP Principles:
🔷 Inheritance:
Inheritance allows one class to acquire properties and methods of another class, enabling
code reusability.
Types of Inheritance:
Single Inheritance: One subclass inherits from one superclass.
Multilevel Inheritance: A class inherits from a class which in turn inherits from
another class.
Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
🔷 Polymorphism:
Polymorphism means "many forms", allowing the same method to behave differently
based on the context.
Types of Polymorphism:
Compile-time (Method Overloading): Same method name with different
parameters.
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Run-time (Method Overriding): Subclass provides specific implementation for
a method declared in the superclass.
class Animal {
void sound() {
System.out.println("Generic animal sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
🔷 Encapsulation:
Encapsulation binds data and code into a single unit, and restricts access using private
variables with getters/setters.
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
🔷 Abstraction:
Abstraction hides internal implementation and only shows essential features to the user.
Achieved via abstract classes or interfaces.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
✅ Conclusion:
Understanding Inheritance and Polymorphism is vital for building scalable and
maintainable applications. OOP enhances software development by promoting reuse,
flexibility, and clarity.