Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Object Oriented Programming (OOP)

Encapsulation and Abstraction

Encapsulation:

Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data (variables) and methods that operate on that data into a single unit known as a class. Encapsulation restricts direct access to some of an object's components and prevents the accidental modification of data.

Abstraction:

Abstraction is the process of hiding the complex reality while exposing only the necessary parts. In Java, abstraction is achieved through abstract classes and interfaces. An abstract class can have abstract (unimplemented) methods, providing a blueprint for its subclasses. Interfaces define abstract methods that implementing classes must provide.

Access Modifiers (public, private, protected):

Access Modifiers:

Access modifiers define the visibility and accessibility of classes, methods, and fields in Java. There are four types of access modifiers:

  • public: Accessible from any class.

  • private: Accessible only within the same class.

  • protected: Accessible within the same package and subclasses.

  • default (no modifier): Accessible within the same package.

Encapsulation and Getters/Setters:

Encapsulation with Getters and Setters:

Encapsulation can be implemented by making the instance variables private and providing public getter and setter methods to access and modify these variables, ensuring data integrity and security.

class Car {
    private String brand;  // Private variable

    // Getter method
    public String getBrand() {
        return brand;
    }

    // Setter method
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

In this example, brand is private, so it cannot be accessed directly from outside the class. The getBrand() method allows read access, and the setBrand(String brand) method allows modification while controlling the access to the brand variable.

Abstract Classes and Interfaces:

Abstract Classes:

Abstract classes are classes that cannot be instantiated and can contain abstract methods (methods without implementation). Abstract classes are useful for providing a common base for subclasses.

abstract class Shape {
    abstract void draw();  // Abstract method without implementation

    void commonMethod() {
        System.out.println("This is a common method.");
    }
}

In this example, Shape is an abstract class with an abstract method draw(). Subclasses of Shape must provide an implementation for the draw() method.

Interfaces:

Interfaces in Java are similar to abstract classes, but they can only contain abstract methods and cannot have instance variables. Classes implement interfaces and provide implementations for all abstract methods declared in the interface.

interface Drawable {
    void draw();  // Abstract method without implementation
}

In this example, Drawable is an interface with an abstract method draw(). Classes that implement the Drawable interface must provide an implementation for the draw() method.

Example Code:

// Encapsulation and Abstraction
class BankAccount {
    private double balance;

    // Constructor
    public BankAccount(double balance) {
        this.balance = balance;
    }

    // Getter and Setter for balance
    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

// Abstract Class
abstract class Shape {
    abstract void draw();  // Abstract method without implementation

    void commonMethod() {
        System.out.println("This is a common method.");
    }
}

// Interface
interface Drawable {
    void draw();  // Abstract method without implementation
}

public class Main {
    public static void main(String[] args) {
        // Encapsulation and Abstraction Example
        BankAccount account = new BankAccount(1000);
        System.out.println("Account Balance: $" + account.getBalance());

        // Abstract Class Example
        Shape shape = new Shape() {
            @Override
            void draw() {
                System.out.println("Drawing a shape.");
            }
        };
        shape.draw();  // Output: Drawing a shape.
        shape.commonMethod();  // Output: This is a common method.

        // Interface Example
        Drawable drawable = new Drawable() {
            @Override
            public void draw() {
                System.out.println("Drawing something.");
            }
        };
        drawable.draw();  // Output: Drawing something.
    }
}

In this example, we demonstrate encapsulation with the BankAccount class, abstraction with the Shape abstract class, and interfaces with the Drawable interface. Each concept is illustrated with an example class or interface and its usage in the Main class.

PreviousInheritance and PolymorphismNextReading and Writing Binary File

Last updated 1 year ago