Java OOP Cheat Sheet

Core OOP Concepts



Class


  • A blueprint for creating objects.
  • Defines attributes (fields) and behaviors (methods).

Example

Java
Copy
public class Car {
    private String model;
    private int year;
    public void drive() {
        System.out.println("Driving...");
    }
}

Object


  • An instance of a class.

Example

Car myCar = new Car();

Inheritance


  • Mechanism where one class acquires the properties and behaviors of another.
  • Promotes code reusability.

Example

Java
Copy
public class ElectricCar extends Car {
    private int batteryCapacity;
    public void charge() {
        System.out.println("Charging...");
    }
}

Encapsulation


  • Wrapping data (fields) and code (methods) together as a single unit.
  • Data hiding is achieved using access modifiers (private, protected, public).

Example

Java
Copy
public class BankAccount {
    private double balance;
    public void deposit(double amount) {
        balance += amount;
    }
    public double getBalance() {
        return balance;
    }
}

Polymorphism


  • The ability to present the same interface for different underlying forms (data types).
  • Achieved through method overloading (compile-time) and method overriding (runtime).

Example (Overloading)

Java
Copy
public class MathOperations {
    public int add(int a, int b) {
        return a + b;
    }
    public double add(double a, double b) {
        return a + b;
    }
}

Example (Overriding)

Java
Copy
public class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}
public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

Abstraction


  • Hiding the implementation details and exposing only the essential features.
  • Achieved using abstract classes and interfaces.

Example (Abstract Class)

Java
Copy
public abstract class Shape {
    abstract void draw();
}
public class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing Circle");
    }
}

Example (Interface)

Java
Copy
public interface Drawable {
    void draw();
}
public class Rectangle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
}

Key OOP Principles in Java



Access Modifiers


  • Private: Accessible only within the declared class.
  • Default (Package-Private): Accessible within classes in the same package.
  • Protected
  • : Accessible within the same package and subclasses.
  • Public
  • : Accessible from any other class.

"this" Keyword


  • Refers to the current instance of a class.
  • Used to differentiate between instance variables and parameters with the same name.
  • Example
  • Java
    Copy
    public class Car {
        private String model;
        public Car(String model) {
            this.model = model;
        }
    }
    

    "super" Keyword


    • Refers to the parent class.
    • Used to call the parent class's methods or constructors.

    Example

    Java
    Copy
    public class ElectricCar extends Car {
        private int batteryCapacity;
        public ElectricCar(String model, int batteryCapacity) {
            super(model);
            this.batteryCapacity = batteryCapacity;
        }
    }
    

    Static Keyword


    • Used for class-level variables and methods.
    • Static members belong to the class rather than any specific instance.

    Example

    Java
    Copy
    public class MathUtility {
        public static final double PI = 3.14159;
        public static int add(int a, int b) {
            return a + b;
        }
    }
    

    Final Keyword


    • Final Class: Cannot be subclassed.
    • Final Method: Cannot be overridden by subclasses.
    • Final Variable: Value cannot be changed once assigned.

    Example

    Java
    Copy
    public final class Constants {
        public static final double GRAVITY = 9.8;
    }
    

    Abstract Classes vs Interfaces


    Abstract Class

    • Can have abstract and non-abstract methods.
    • Can have constructors, fields, and access modifiers.
    • Supports single inheritance.

    Example

    Java
    Copy
    public abstract class Animal {
        private String name;
        public Animal(String name) {
            this.name = name;
        }
        abstract void makeSound();
    }
    

    Interface

    • Can have only abstract methods (before Java 8) or default/static methods (Java 8 and later).
    • All fields are public, static, and final by default. Supports multiple inheritance.

    Example

    Java
    Copy
    public interface Flyable {
        void fly();
    }
    

    Object Class Methods



    • equals(): Compares two objects for equality.
    • hashCode(): Returns a hash code value for the object.
    • toString(): Returns a string representation of the object.
    • clone(): Creates a copy of the object.
    • finalize(): Called by the garbage collector before an object is destroyed.

    Common Design Patterns



    Singleton


    Ensures a class has only one instance and provides a global point of access to it.

    Example

    Java
    Copy
    public class Singleton {
        private static Singleton instance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    

    Factory


    Provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

    Example

    Java
    Copy
    public interface Shape {
        void draw();
    }
    public class Circle implements Shape {
        public void draw() {
            System.out.println("Circle");
        }
    }
    public class ShapeFactory {
        public Shape getShape(String shapeType) {
            if (shapeType == null) {
                return null;
            }
            if (shapeType.equalsIgnoreCase("CIRCLE")) {
                return new Circle();
            }
            return null;
        }
    }
    

    Observer


    Defines a dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

    Example

    Java
    Copy
    public class ObserverPatternDemo {
        public static void main(String[] args) {
            Subject subject = new Subject();
            new HexObserver(subject);
            subject.setState(15);
        }
    }
    

    Decorator


    Allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

    Example

    Java
    Copy
    public interface Shape {
        void draw();
    }
    public class Circle implements Shape {
        public void draw() {
            System.out.println("Shape: Circle");
        }
    }
    public abstract class ShapeDecorator implements Shape {
        protected Shape decoratedShape;
        public ShapeDecorator(Shape decoratedShape) {
            this.decoratedShape = decoratedShape;
        }
        public void draw() {
            decoratedShape.draw();
        }
    }
    public class RedShapeDecorator extends ShapeDecorator {
        public RedShapeDecorator(Shape decoratedShape) {
            super(decoratedShape);
        }
        public void draw() {
            decoratedShape.draw();
            setRedBorder(decoratedShape);
        }
        private void setRedBorder(Shape decoratedShape) {
            System.out.println("Border Color: Red");
        }
    }
    

    Advanced OOP Concepts



    Coupling


    • Degree of interdependence between software modules.
    • Loose Coupling: Modules can be changed independently of each other.
    • Tight Coupling: Changes in one module necessitate changes in another.

    Cohesion


    • Degree to which elements of a module belong together.
    • High cohesion is preferable; it means a module or class is focused on a single task.

    Dependency Injection


    • A technique whereby one object supplies the dependencies of another object.
    • Promotes loose coupling.

    SOLID Principles


    • Single Responsibility Principle: A class should have only one reason to change.
    • Open/Closed Principle: Software entities should be open for extension, but closed for modification.
    • Liskov Substitution Principle: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
    • Interface Segregation Principle: Clients should not be forced to depend upon interfaces they do not use.
    • Dependency Inversion Principle: Depend upon abstractions, not concretions.