Understanding OOP -Inheritance, Polymorphism, Encapsulation
1. Quick Recap: What is OOP?
OOP (Object-Oriented Programming) is about designing programs around objects that have data (attributes) and behaviors (methods).
Main OOP principles:
-
Inheritance – Reuse code from one class in another
-
Polymorphism – One method, many forms
-
Encapsulation – Protect data by controlling access
-
Abstraction – Hide implementation details (covered later)
2. Access Modifiers in Java
Access modifiers control visibility of classes, methods, and variables.
Modifier | Access Level |
---|---|
public | Accessible from anywhere |
protected | Accessible in same package and subclasses |
default (no keyword) | Accessible in same package only |
private | Accessible only inside the same class |
3. Inheritance – Reusing Code
Inheritance allows one class (child/subclass) to get properties and methods from another class (parent/superclass).
Example:
Output:
Types of Inheritance in Java
-
Single – One parent, one child
-
Multilevel – Child → Grandchild → Great-grandchild
-
Hierarchical – Multiple children from one parent
(Java doesn’t support multiple inheritance with classes, but supports it with interfaces.)
4. Method Overriding – Changing Inherited Behavior
If a subclass wants a different version of a parent method, it can override it.
5. Polymorphism – Many Forms
Polymorphism allows the same method call to behave differently depending on the object.
Example:
6. Encapsulation – Data Protection
Encapsulation means hiding class variables and giving controlled access through getters and setters.
Example:
7. Mini Practice Exercises
Task 1: Create a class Employee
with name
and salary
. Create a subclass Manager
that adds a department
property and overrides a method displayDetails()
.
Task 2: Create a superclass Shape
and subclasses Circle
and Rectangle
. Implement area()
method in each.
Task 3: Create a Student
class with private variables name
and marks
, and use getters and setters to access them.
8. What’s Next?
In Blog 6, we’ll explore:
-
Arrays (1D, 2D)
-
String handling (
String
,StringBuilder
,StringBuffer
) -
Real examples with arrays and strings
💡 Tip: OOP becomes easier when you relate it to real life think about how cars, people, or phones can be modeled with classes and objects.
great content
ReplyDelete