`

Classes and Interfaces:


1. Object-Oriented Programming (OOP) in Java

OOP is a programming paradigm that uses objects to model real-world entities and their behaviors. Java is a fully object-oriented programming language that implements OOP principles.

Key Principles of OOP in Java:

  1. Encapsulation:
    • Encapsulation is the concept of bundling data (fields) and methods (functions) that operate on the data into a single unit (class).
    • It provides control over the access to the data using access modifiers (private, protected, public).
    • Example:
      class BankAccount {
          private double balance;
      
          public void deposit(double amount) {
              balance += amount;
          }
      
          public double getBalance() {
              return balance;
          }
      }
      
  2. Inheritance:
    • Allows a class (child class) to inherit the properties and behaviors of another class (parent class).
    • Promotes code reuse and hierarchy modeling.
    • Example:
      class Animal {
          void eat() {
              System.out.println("This animal eats food.");
          }
      }
      
      class Dog extends Animal {
          void bark() {
              System.out.println("Dog barks.");
          }
      }
      
  3. Polymorphism:
    • The ability of a single interface or method to represent different forms.
    • Two types:
      • Compile-Time Polymorphism (Method Overloading): Multiple methods with the same name but different parameters.
      • Run-Time Polymorphism (Method Overriding): A subclass provides its own implementation of a method already defined in the parent class.
    • Example:
      class Shape {
          void draw() {
              System.out.println("Drawing a shape");
          }
      }
      
      class Circle extends Shape {
          @Override
          void draw() {
              System.out.println("Drawing a circle");
          }
      }
      
  4. Abstraction:
    • The process of hiding implementation details and showing only the necessary functionality.
    • Achieved through:
      • Abstract Classes: Classes that cannot be instantiated and may contain abstract methods (without implementation).
      • Interfaces: Define a contract (methods) that implementing classes must follow.
    • Example of Abstract Class:
      abstract class Vehicle {
          abstract void move();
      }
      
      class Car extends Vehicle {
          @Override
          void move() {
              System.out.println("Car is moving");
          }
      }
      

2. Classes in Java

A class is a blueprint or template for creating objects. It defines fields (variables) and methods (functions) to describe the behavior and state of objects.

Structure of a Class:

class ClassName {
    // Fields (attributes)
    int id;
    String name;

    // Constructor
    ClassName(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Methods (behaviors)
    void displayInfo() {
        System.out.println("ID: " + id + ", Name: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        ClassName obj = new ClassName(1, "Java");
        obj.displayInfo();
    }
}

Key Points:


3. Interfaces in Java

An interface in Java is a reference type that defines a set of abstract methods. It specifies what a class must do, but not how to do it.

Key Features of Interfaces:

  1. All methods in an interface are implicitly public and abstract (before Java 8).
  2. An interface cannot have instance fields (only constants using public static final).
  3. From Java 8, interfaces can have:
    • Default Methods: Methods with a default implementation.
    • Static Methods: Methods that belong to the interface and not the implementing class.
  4. From Java 9, interfaces can have private methods to reuse code within default methods.

Declaring and Implementing an Interface:

interface Animal {
    void eat();  // Abstract method
    void sleep();
}

class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("Dog is eating");
    }

    @Override
    public void sleep() {
        System.out.println("Dog is sleeping");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.sleep();
    }
}

Default Methods Example (Java 8+):

interface Vehicle {
    void start();

    default void stop() {
        System.out.println("Vehicle stopped.");
    }
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car started.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start();
        car.stop();  // Uses default implementation
    }
}

Static Methods in Interfaces:

interface Calculator {
    static int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int result = Calculator.add(5, 3);
        System.out.println("Result: " + result);
    }
}

Difference Between Classes and Interfaces:

Feature Class Interface
Instantiation Can be instantiated (via objects). Cannot be instantiated directly.
Implementation Defines both methods and their bodies. Contains only abstract methods (pre-Java 8).
Multiple Inheritance Not supported directly. Supported via multiple implemented interfaces.
Access Modifiers Fields and methods can have various access modifiers. All fields are public static final. Methods are public and abstract (pre-Java 8).

4. When to Use Classes and Interfaces