OOP Concepts Detailed Java Laptop Example
OOP Concepts Detailed Java Laptop Example
This document explains the fundamental OOP concepts in Java using real-world examples.
We'll explore Encapsulation, Abstraction, Inheritance, and Polymorphism with examples,
along with information on JDK, JRE, and JVM.
1. Encapsulation
Encapsulation is the concept of wrapping data and methods into a single unit, called a class.
It restricts access to certain components to ensure controlled modification and data
integrity. In Java, encapsulation is achieved using private variables and public getter and
setter methods.
Example:
class Laptop {
private String brand;
private int ramSize;
private double price;
2. Abstraction
Abstraction is the process of hiding the implementation details and showing only the
necessary features of an object. It helps in reducing complexity. Java provides abstraction
through abstract classes and interfaces.
Example:
interface ElectronicDevice {
void powerOn();
void powerOff();
}
3. Inheritance
Inheritance allows one class to inherit fields and methods from another class, promoting
code reuse. In Java, inheritance is achieved using the 'extends' keyword.
Example:
4. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon. It
has two types: Method Overloading and Method Overriding.
Method Overloading is achieved by defining multiple methods with the same name but
different parameters within a class.
Example:
class Laptop {
private String brand;
private int ramSize;
private double price;
// Overloaded method
public void displayInfo(String feature) {
System.out.println("Brand: " + brand + ", RAM: " + ramSize + "GB, Price: $" + price + ",
Feature: " + feature);
}
Example: