Java OOPs Concepts
Java OOP (Object Oriented Programming) Concepts
Object-Oriented Programming (OOP) refers to languages that use objects in programming. It aims to implement
real-world entities like inheritance, polymorphism, and encapsulation.
Example: Object and Class in Java
import java.io.*;
class Numbers {
private int a;
private int b;
public void sum() { System.out.println(a + b); }
public void sub() { System.out.println(a - b); }
public static void main(String[] args) {
Numbers obj = new Numbers();
obj.a = 1;
obj.b = 2;
obj.sum();
obj.sub();
}
}
Java Class
A class is a blueprint from which objects are created. It represents properties and methods common to all
objects of one type.
Java Object
An object is a basic unit of OOP that represents real-world entities. Objects have:
- **State:** Attributes of an object.
- **Behavior:** Methods of an object.
- **Identity:** Unique name for interaction.
4 Pillars of Java OOPs Concepts
1. **Abstraction** - Hiding implementation details while showing only essential features.
2. **Encapsulation** - Wrapping data and methods into a single unit (class).
3. **Inheritance** - One class can inherit fields and methods from another.
4. **Polymorphism** - The ability of an object to take many forms (Method Overloading & Overriding).
Example: Encapsulation in Java
class Employee {
Java OOPs Concepts
private int empid;
private String ename;
public void set_id(int empid) { this.empid = empid; }
public void set_name(String ename) { this.ename = ename; }
public int get_id() { return empid; }
public String get_name() { return ename; }
}
public class Main {
public static void main(String args[]) {
Employee e = new Employee();
e.set_id(78);
e.set_name("John");
System.out.println("Employee id: " + e.get_id());
System.out.println("Employee Name: " + e.get_name());
}
}
Conclusion
Java OOP concepts provide structure, modularity, and efficiency in programming. Using classes and objects,
developers can create scalable and maintainable applications efficiently.
FAQs - Java OOPs Concepts
1. **What is OOPs concept in Java?**
OOPs (Object-Oriented Programming) is a programming paradigm based on the concept of objects, which contain
data and code.
2. **Why is OOPs important in Java?**
OOPs helps in structuring code in a manageable way, promoting reusability, modularity, and flexibility.
3. **What are the main principles of OOPs in Java?**
Encapsulation, Inheritance, Polymorphism, and Abstraction.
4. **How is OOPs implemented in Java?**
Through classes and objects, where each object has attributes and methods.
5. **What are the advantages of using OOPs in Java?**
Reusability, modularity, flexibility, scalability, and easier maintenance.