Object-Oriented Programming (OOP) in Java
Java is a pure object-oriented programming language (with a few
exceptions like primitive types). OOP is a programming paradigm that
uses "objects" to design applications. Objects are instances of classes,
which define properties (fields) and behaviors (methods).
🧱 Core Concepts of OOP in Java
1. Class
A class is a blueprint for creating objects. It defines fields (variables)
and methods (functions).
java
CopyEdit
public class Car {
// Fields
String color;
int speed;
// Method
void drive() {
System.out.println("The car is driving.");
}
}
2. Object
An object is an instance of a class.
java
CopyEdit
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Create an object
myCar.color = "Red";
myCar.speed = 100;
myCar.drive(); // Call the method
}
}
3. Encapsulation
Encapsulation is the process of hiding internal data and only allowing
access through public methods (getters/setters).
java
CopyEdit
public class Person {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
4. Inheritance
Inheritance allows one class (child/subclass) to inherit properties and
methods from another class (parent/superclass).
java
CopyEdit
public class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
public class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
5. Polymorphism
Polymorphism means many forms — the same method name can behave
differently based on the object.
a) Method Overriding (Runtime Polymorphism)
java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
b) Method Overloading (Compile-time Polymorphism)
java
CopyEdit
class Math {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
6. Abstraction
Abstraction hides implementation details and only shows essential
features. It is achieved using abstract classes and interfaces.
a) Abstract Class
java
CopyEdit
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
b) Interface
java
CopyEdit
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
🎯 Summary
OOP Concept Description
Class Blueprint for creating objects
Object Instance of a class
Protect data using access
Encapsulation
modifiers
Inheritance Share behavior between classes
One interface, many
Polymorphism
implementations
Hide internal details, show
Abstraction
essentials