OOP_Concepts_with_Java_Examples
OOP_Concepts_with_Java_Examples
A class is a blueprint for creating objects. Each object is an instance of a class. For example, a Car class can
have properties like model and year, and methods like displayInfo().
Example: Creating a simple Car class.
class Car {
String model;
int year;
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
2. Encapsulation
Encapsulation is the concept of wrapping data (variables) and code (methods) together as a single unit. It
helps protect data from unauthorized access using access modifiers like private.
Example: Protecting balance in a BankAccount class.
class BankAccount {
private double balance; // private = encapsulated
Inheritance allows one class to inherit the properties and methods of another class. This helps in code reuse
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
4. Polymorphism - Overriding
Polymorphism means many forms. In method overriding, a subclass provides a specific implementation of a
class Animal {
void sound() {
System.out.println("Generic animal sound");
}
}
In method overloading, multiple methods have the same name but differ in the type or number of parameters.
Method Overloading (Compile-time Polymorphism)
class Calculator {
int add(int a, int b) {
return a + b;
}
5. Abstraction
Abstraction means hiding complex implementation details and showing only the necessary features. It is
6. Interface
An interface in Java is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Interfaces help achieve full abstraction.
Example: Using interface for multiple behaviors.
interface Printable {
void print();
}