What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects rather than actions or logic alone.
- In Java, almost everything is treated as an object, which makes OOP essential for writing scalable and maintainable programs.
- It helps model real-world entities in code, making programs easier to understand and manage.
Key OOP Concepts
- Class
- Blueprint or template for creating objects.
- Defines properties (attributes) and behaviors (methods).
- Example:
class Car { String color; int speed; void drive() {} }
- Object
- An instance of a class.
- Represents a real-world entity with state and behavior.
- Example:
Car myCar = new Car();
- Inheritance
- Mechanism to create a new class from an existing class.
- Promotes code reuse.
- Example:
class ElectricCar extends Car { int batteryCapacity; }
- Polymorphism
- Ability of objects to take many forms.
- Achieved via method overloading and overriding.
- Example: Same method name behaves differently in different classes.
- Encapsulation
- Hiding internal details of a class and exposing only necessary parts.
- Achieved using
privatevariables andpublicgetter/setter methods. - Example:
private int balance; public int getBalance() { return balance; }
- Abstraction
- Focus on essential features while hiding unnecessary details.
- Implemented using abstract classes and interfaces.
Benefits of Learning OOP for Beginners
- Encourages modular and organized code.
- Makes programs reusable and easier to maintain.
- Mirrors real-world problem solving, making concepts intuitive.
- Essential for modern Java applications, including GUI apps, web services, and Android development.
1. Install Java Development Kit (JDK)

- Download the JDK from the official Oracle website or OpenJDK.
- Follow the installation instructions for your operating system (Windows, macOS, or Linux).
Set Environment Variables (Windows Example):
- Open System Properties → Advanced → Environment Variables.
- Add a new system variable
JAVA_HOMEpointing to the JDK installation folder. - Edit the
Pathvariable and add%JAVA_HOME%\bin. - Test the setup by running
java -versionandjavac -versionin the command prompt.
2. Choose an IDE
A good IDE makes coding easier with features like syntax highlighting, debugging, and auto-completion. Popular choices:
- IntelliJ IDEA – widely used, beginner-friendly, powerful.
- Eclipse – free, highly customizable.
- VS Code – lightweight editor with Java extensions.
Tips:
- Beginners can start with IntelliJ Community Edition or VS Code for simplicity.
- Use the built-in terminal in the IDE to compile and run programs.
3. Use Online Java Compilers (Optional for Quick Practice)
For quick testing or if installation is not possible:
Benefits:
- No installation required.
- Good for experimenting with small code snippets or learning Java syntax.
1. What is a Class?
A class is a blueprint for creating objects. It defines attributes (fields) and behaviors (methods) that the objects of that class will have.
Example Concept:
Think of a class Car — it defines what a car has (color, speed) and can do (drive, stop).
2. What is an Object?
An object is an instance of a class. Using the Car example: each specific car (like a red car moving at 120 km/h) is an object created from the Car class.
- Multiple objects can be created from the same class.
- Each object has its own copy of attributes.
3. Example Code: Creating a Class and Objects
// Define a class
class Car {
String color;
int speed;
// Method to display car details
void displayDetails() {
System.out.println("Car color: " + color);
System.out.println("Car speed: " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
// Create first object
Car car1 = new Car();
car1.color = "Red";
car1.speed = 120;
car1.displayDetails();
// Create second object
Car car2 = new Car();
car2.color = "Blue";
car2.speed = 90;
car2.displayDetails();
}
}
Output:
Car color: Red
Car speed: 120 km/h
Car color: Blue
Car speed: 90 km/h
4. Key Points
- A class is like a blueprint.
- An object is an actual instance of that blueprint.
- Multiple objects can exist with different values for the attributes.
- Methods define behavior that objects of the class can perform.
1. What is a Constructor?

A constructor is a special method in Java used to initialize objects when they are created.
- It has the same name as the class.
- It does not have a return type, not even
void. - It is automatically called when an object is created.
Purpose: To set initial values for object attributes.
2. Types of Constructors
a) Default Constructor
- Provided by Java if no constructor is defined.
- Initializes objects with default values.
class Car {
String color;
int speed;
// Default constructor
Car() {
color = "Unknown";
speed = 0;
}
void display() {
System.out.println("Car color: " + color + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
car1.display();
}
}
Output:
Car color: Unknown, Speed: 0
b) Parameterized Constructor
- Allows passing values while creating an object.
- Used to initialize objects with specific values.
class Car {
String color;
int speed;
// Parameterized constructor
Car(String c, int s) {
color = c;
speed = s;
}
void display() {
System.out.println("Car color: " + color + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Red", 120);
Car car2 = new Car("Blue", 90);
car1.display();
car2.display();
}
}
Output:
Car color: Red, Speed: 120
Car color: Blue, Speed: 90
3. Constructor Overloading
- Multiple constructors in a class with different parameter lists.
- Allows creating objects in different ways.
class Car {
String color;
int speed;
Car() { // Default constructor
color = "Unknown";
speed = 0;
}
Car(String c) { // Constructor with one parameter
color = c;
speed = 50;
}
Car(String c, int s) { // Constructor with two parameters
color = c;
speed = s;
}
void display() {
System.out.println("Car color: " + color + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car("Green");
Car car3 = new Car("Yellow", 150);
car1.display();
car2.display();
car3.display();
}
}
Output:
Car color: Unknown, Speed: 0
Car color: Green, Speed: 50
Car color: Yellow, Speed: 150
Key Points
- Constructors initialize objects.
- Default constructor: no parameters, initializes with default values.
- Parameterized constructor: initializes with user-defined values.
- Constructor overloading allows multiple ways to create objects.
What is Inheritance?
Inheritance is a fundamental OOP concept where a class (child/subclass) acquires properties and methods from another class (parent/superclass).
Purpose:
- Reuse existing code.
- Create a logical hierarchy between classes.
Keyword in Java: extends
2. Types of Inheritance
a) Single Inheritance
One child class inherits from one parent class.
// Parent class
class Vehicle {
String brand = "Generic Vehicle";
void honk() {
System.out.println("Beep beep!");
}
}
// Child class
class Car extends Vehicle {
String model = "Sedan";
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
System.out.println(car1.brand); // inherited from Vehicle
System.out.println(car1.model); // from Car
car1.honk(); // inherited method
}
}
Output:
Generic Vehicle
Sedan
Beep beep!
b) Multilevel Inheritance
A class inherits from a child class, forming a chain.
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
class SportsCar extends Car {
void turbo() {
System.out.println("Turbo mode ON!");
}
}
public class Main {
public static void main(String[] args) {
SportsCar sc = new SportsCar();
sc.start(); // Vehicle method
sc.drive(); // Car method
sc.turbo(); // SportsCar method
}
}
Output:
Vehicle started
Car is driving
Turbo mode ON!
c) Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
class Bike extends Vehicle {
void ride() {
System.out.println("Bike is riding");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
Bike b = new Bike();
c.start();
c.drive();
b.start();
b.ride();
}
}
Output:
Vehicle started
Car is driving
Vehicle started
Bike is riding
3. Benefits of Inheritance
- Code Reusability: Avoid rewriting common methods and attributes.
- Logical Hierarchy: Represents real-world relationships.
- Extensibility: Easily add new features in child classes.
1. What is Polymorphism?
Polymorphism is an OOP concept that allows one entity (method or object) to take multiple forms.
In Java, it mainly appears as:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)
Importance:
- Makes code more flexible and reusable.
- Allows implementing multiple behaviors for the same method or object.
2. Compile-Time Polymorphism (Method Overloading)
Occurs when multiple methods in the same class have the same name but different parameters.
The compiler decides which method to call based on parameter types or number.
class Calculator {
// Add two integers
int add(int a, int b) {
return a + b;
}
// Add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Add two doubles
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // calls add(int, int)
System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int)
System.out.println(calc.add(2.5, 3.5)); // calls add(double, double)
}
}
Output:
15
30
6.0
3. Runtime Polymorphism (Method Overriding)
Occurs when a child class provides its own implementation of a method defined in the parent class.
The method that gets called is determined at runtime based on the object type.
// Parent class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Child class
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog(); // Runtime polymorphism
myAnimal.sound(); // Animal's method
myDog.sound(); // Dog's overridden method
}
}
Output:
Animal makes a sound
Dog barks
4. Why Polymorphism is Important
- Flexibility: Write generalized code that works for multiple types.
- Reusability: Avoid rewriting code for similar behavior.
- Extensibility: Add new classes without changing existing code.
- Supports real-world modeling (e.g., different animals making different sounds).
1. What is Encapsulation?
Encapsulation is an OOP concept that restricts direct access to class data and allows controlled access through methods.
- Data hiding improves security and prevents unauthorized modification.
- Getters and setters are used to read and update private fields safely.
2. Benefits of Encapsulation
- Protects data from unwanted changes.
- Makes code easier to maintain.
- Allows validation before changing data (e.g., checking if a balance is positive).
3. Example: Bank Account
class BankAccount {
// Private variables (data hiding)
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String accountHolder, double balance) {
this.accountHolder = accountHolder;
if (balance >= 0) {
this.balance = balance;
} else {
this.balance = 0;
System.out.println("Initial balance cannot be negative. Set to 0.");
}
}
// Getter for accountHolder
public String getAccountHolder() {
return accountHolder;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter for balance with validation
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("John Doe", 500);
System.out.println("Account Holder: " + account.getAccountHolder());
System.out.println("Balance: " + account.getBalance());
account.deposit(200);
account.withdraw(100);
System.out.println("Updated Balance: " + account.getBalance());
}
}
4. Output
Account Holder: John Doe
Balance: 500.0
Deposited: 200.0
Withdrawn: 100.0
Updated Balance: 600.0
Key Points
- Variables
accountHolderandbalanceare private and cannot be accessed directly. - Methods
getBalance(),deposit(), andwithdraw()provide controlled access. - Validation ensures that the balance cannot go negative or invalid amounts be deposited/withdrawn.
1. What is Abstraction?
Abstraction is an OOP concept that hides implementation details and shows only the essential features of an object.
- It focuses on what an object does, not how it does it.
- Achieved in Java using:
- Abstract classes (can have both abstract and concrete methods)
- Interfaces (all methods abstract by default in older versions; Java 8+ allows default and static methods)
2. Why Use Abstraction?
- Helps in managing complexity by hiding unnecessary details.
- Promotes loose coupling and reusability.
- Provides a blueprint for other classes.
3. Example: Shape Interface
// Abstract representation of a Shape
interface Shape {
void draw(); // Abstract method
double getArea(); // Abstract method
}
// Circle class implements Shape
class Circle implements Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
public void draw() {
System.out.println("Drawing a Circle");
}
public double getArea() {
return Math.PI * radius * radius;
}
}
// Rectangle class implements Shape
class Rectangle implements Shape {
private double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public void draw() {
System.out.println("Drawing a Rectangle");
}
public double getArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
circle.draw();
System.out.println("Circle area: " + circle.getArea());
rectangle.draw();
System.out.println("Rectangle area: " + rectangle.getArea());
}
}
4. Output
Drawing a Circle
Circle area: 78.53981633974483
Drawing a Rectangle
Rectangle area: 24.0
5. Key Points
Shapedefines what methods every shape should have, without specifying how they are implemented.CircleandRectangleimplement the interface, providing their own behavior.- Using abstraction, you can add more shapes without changing existing code.
- Abstract classes work similarly but can include concrete methods as well.
you may also like to read these posts:
Smart Budget Planning for Families: A Practical Guide to Financial Harmony
Discover the Beauty of Indonesian Traditional Fashion Styles
Learn Java Easily Online with Simple Coding Examples
Easy Core Java Tutorials for Beginners to Start Coding
1. Why Combine OOP Concepts?
Using multiple OOP concepts together in a project helps you:
- Organize code efficiently with classes and objects.
- Reuse code via inheritance.
- Allow flexibility with polymorphism (method overriding/overloading).
- Protect data using encapsulation.
- Hide implementation details using abstraction.
2. Example Project: Student Management System
OOP Concepts Applied:
- Class & Object: Represent students and courses.
- Encapsulation: Keep student details private with getters/setters.
- Inheritance: Specialized student types (e.g., Undergraduate, Graduate).
- Polymorphism: Overriding methods for different student types.
// Base class
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
// Subclass using Inheritance and Polymorphism
class Undergraduate extends Student {
private String major;
public Undergraduate(String name, int age, String major) {
super(name, age);
this.major = major;
}
@Override
public void displayInfo() { // Method overriding
super.displayInfo();
System.out.println("Major: " + major);
}
}
public class StudentManagement {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
Undergraduate s2 = new Undergraduate("Bob", 22, "Computer Science");
s1.displayInfo();
System.out.println();
s2.displayInfo();
}
}
Output:
Name: Alice, Age: 20
Name: Bob, Age: 22
Major: Computer Science
3. Library Management System Example
Concepts Applied:
- Classes & Objects: Book, Member, Library.
- Encapsulation: Private book details with getters/setters.
- Polymorphism: Different member types with custom borrowing rules.
- Inheritance: Specialized member classes (StudentMember, TeacherMember).
4. Banking System Example
Concepts Applied:
- Class & Object: Account class.
- Encapsulation: Keep balance private, provide deposit/withdraw methods.
- Inheritance: SavingsAccount and CurrentAccount inherit Account.
- Polymorphism: Override interest calculation methods for different account types.
- Abstraction: Use abstract class
Accountto define general account behavior.
5. Tips for Beginners
- Start with small projects (e.g., Student Management) before large systems.
- Identify entities and represent them as classes.
- Decide which OOP concepts apply to each entity.
- Use inheritance for specialized classes.
- Apply polymorphism for behaviors that differ between classes.
- Protect sensitive data with encapsulation.
- Gradually add abstraction to hide implementation details.
Tips for Practicing OOP
- Start Small
- Begin with simple examples like a
CarorBankAccountclass. - Practice creating objects, calling methods, and using constructors.
- Begin with simple examples like a
- Combine Concepts Gradually
- Once comfortable with classes and objects, introduce inheritance and polymorphism.
- Example: Extend a
BankAccountclass intoSavingsAccountandCurrentAccount.
- Write Clean, Modular Code
- Use separate classes for different entities.
- Keep methods short and focused on a single task.
- Name variables and methods clearly for readability.
- Experiment and Modify
- Add new features to your examples (e.g., additional account operations or student attributes).
- Try overriding methods or creating new constructors.
- Practice Debugging
- Learn to read compiler errors carefully.
- Fix issues related to data encapsulation, inheritance, or method overriding.
- Use
System.out.println()or IDE debuggers to trace program flow.
- Work on Mini Projects
- Combine multiple OOP concepts in small projects like:
- Student Management System
- Library Management System
- Simple Banking Application
- Combine multiple OOP concepts in small projects like:
- Review and Refactor
- Revisit old code and improve structure using OOP principles.
- Apply abstraction and interfaces where appropriate.
Faqs:
What is the importance of object-oriented programming in Java?
Object-oriented programming (OOP) allows you to structure code using classes and objects, making it reusable, modular, and easier to maintain, which is essential in Java development.
Can beginners practice OOP examples without installing Java?
Yes, beginners can use online Java compilers like JDoodle, Replit, or CodeGym to run object-oriented Java examples for learners without setting up a local environment.
How many examples should I practice to understand OOP?
Practicing 5–10 diverse examples covering classes, objects, inheritance, polymorphism, and encapsulation is usually enough to build a strong foundational understanding.
Can I combine these OOP examples into a small project?
Absolutely! Beginners can create projects like a student management system or library system by combining multiple OOP concepts, which reinforces learning through practical application.
What should I learn after mastering these basic OOP examples?
After mastering basic OOP concepts, you can explore advanced topics like interfaces, abstract classes, file handling, collections, and GUI-based Java applications to further enhance your programming skills.
Conclusion
Practicing object-oriented Java examples for learners is essential for building a solid foundation in Java programming. By understanding and implementing classes, objects, inheritance, polymorphism, encapsulation, and abstraction, beginners can write clean, reusable, and maintainable code. Consistent practice with real examples prepares learners for advanced Java projects and real-world application development.
