Object-Oriented Programming (OOP) in Java
Understanding Core Concepts with Examples
Introduction
• Java is an Object-Oriented Language.
• OOP makes code reusable, modular, and easier to maintain.
• Four pillars: Inheritance, Polymorphism, Encapsulation, Abstraction.
Classes and Objects
• Class is a blueprint; Object is an instance.
• Example:
• class Student {
• String name;
• int age;
• }
• public class Main {
• public static void main(String[] args) {
• Student s1 = new Student();
• s1.name = "Amit";
• s1.age = 20;
Constructors
• Special method used to initialize objects.
• Example:
• class Student {
• String name;
• Student(String n) { name = n; }
• }
• public class Main {
• public static void main(String[] args) {
• Student s1 = new Student("Ravi");
• System.out.println(s1.name);
• }
Inheritance
• One class can inherit fields & methods of another.
• Example:
• class Animal {
• void sound() { System.out.println("Animal makes sound"); }
• }
• class Dog extends Animal {
• void sound() { System.out.println("Dog barks"); }
• }
• public class Main {
• public static void main(String[] args) {
• Dog d = new Dog();
Polymorphism
• Compile-time (Overloading) and Runtime (Overriding).
• Example:
• class MathOp {
• int add(int a, int b) { return a+b; }
• double add(double a, double b) { return a+b; }
• }
Encapsulation
• Wrapping data and methods into a single unit.
• Use private variables with getter/setter.
• Example:
• class Student {
• private int age;
• public void setAge(int a) { age = a; }
• public int getAge() { return age; }
• }
Abstraction
• Hiding implementation details.
• Achieved using abstract classes.
• Example:
• abstract class Animal {
• abstract void sound();
• }
• class Dog extends Animal {
• void sound() { System.out.println("Dog barks"); }
• }
Interfaces
• Used to achieve multiple inheritance.
• Example:
• interface Animal {
• void sound();
• }
• class Dog implements Animal {
• public void sound() { System.out.println("Dog barks"); }
• }
Access Modifiers
• Control access to classes and members.
• (public, private, protected, default).
• Example:
• public class A {
• private int x = 10;
• public void show() { System.out.println(x); }
• }
Real-life Example
• Bank Account Example using OOP concepts.
• Example:
• class Account {
• protected double balance = 1000;
• void deposit(double amt) { balance += amt; }
• }
• class Savings extends Account {
• void withdraw(double amt) { balance -= amt; }
• }
Conclusion
• Java OOP makes code modular, reusable, and scalable.
• Mastering OOP is essential for real-world projects.