What is OOP in Java?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data (fields) and code (methods). Java is a fully OOP language.
Core Concepts of OOP in Java
1. Class
-
A blueprint/template for creating objects.
-
Defines properties (attributes) and behaviors (methods).
2. Object
-
An instance of a class.
-
Created using the
new
keyword.
Car myCar = new Car();
myCar.color = “Red”;
myCar.accelerate();
3. Encapsulation
-
Wrapping data (variables) and methods into a single unit (class).
-
Data hiding using access modifiers (
private
,public
, etc.).
public class Person {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
4. Inheritance
-
A class inherits properties and methods from another class.
-
Promotes code reuse.
public class Animal {
void eat() {
System.out.println(“Eating…”);
}
}
public class Dog extends Animal {
void bark() {
System.out.println(“Barking…”);
}
}
5. Polymorphism
-
Ability to take many forms.
-
Method overriding and method overloading.
class Animal {
void sound() {
System.out.println(“Animal makes a sound”);
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println(“Meow”);
}
}
6. Abstraction
-
Hiding complex implementation details and showing only essential features.
-
Achieved with abstract classes and interfaces.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println(“Drawing Circle”);
}
}
Simple Example Putting It Together
class Employee {
private String name;
private int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public void display() {
System.out.println(“Name: ” + name + “, ID: ” + id);
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee(“Alice”, 101);
emp.display();
}
}