Java OOPS Concepts: Complete Guide with Examples
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes. Java is a fully object-oriented language that supports OOPS principles like encapsulation, inheritance, polymorphism, and abstraction.
Class and Object in Java
A class is a blueprint used to create objects, while an object is an instance of a class.
Example
class Student {
String name;
int age;
void display() {
System.out.println(name + " " + age);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "John";
s1.age = 20;
s1.display();
}
}
Encapsulation in Java
Encapsulation means wrapping data (variables) and methods into a single unit (class) and restricting direct access using private access modifier.
Example
class Employee {
private int salary;
public void setSalary(int salary) {
this.salary = salary;
}
public int getSalary() {
return salary;
}
}
Here, salary is hidden from outside and accessed using getter and setter methods.
Inheritance in Java
Inheritance allows one class to acquire properties and methods of another class. It promotes code reusability.
Example
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
Dog class inherits the behavior of Animal class.
Polymorphism in Java
Polymorphism means "many forms". It allows one method to behave differently based on input or object type.
Types
- Compile-time (Method Overloading)
- Runtime (Method Overriding)
Method Overloading Example
class MathUtil {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Method Overriding Example
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Abstraction in Java
Abstraction means hiding implementation details and showing only essential features. It is achieved using abstract classes and interfaces.
Abstract Class Example
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with key");
}
}
Interface Example
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
OOPS Summary
- Class → blueprint
- Object → instance of class
- Encapsulation → data hiding
- Inheritance → code reuse
- Polymorphism → multiple behavior
- Abstraction → hide implementation
OOPS FAQ
What are OOPS concepts in Java?
Encapsulation, Inheritance, Polymorphism, and Abstraction.
Why OOPS is important?
It improves code reusability, security, and maintainability.
What is difference between abstraction and encapsulation?
Encapsulation hides data, while abstraction hides implementation details.