Skip to main content

Object oriented programming

Class vs abstract class vs interface vs Object

Class vs Object

The main difference between an object and a class in Java lies in their concept and how they are used in your program:

Class:

  • A class acts as a blueprint or template that defines the properties (variables) and behavior (methods) of objects.
  • It specifies the characteristics that all objects of that class will share.
  • You can think of a class as a recipe that outlines the ingredients (variables) and steps (methods) needed to create a dish (object).
  • A class itself doesn't exist in memory until you create an instance of it.

Object:

  • An object is an instance of a class. It's a concrete realization of the blueprint defined by the class.
  • Each object has its own set of values for the properties (variables) defined in the class.
  • Objects can interact with each other by calling methods on each other.
  • When you create an object using the new keyword, memory is allocated for the object, and the initial values for its properties are set.

Here's a table summarizing the key differences:

Feature Class Object
Concept Blueprint, template Instance of a class
Properties Defines properties (variables) Has its own set of values for properties
Behavior Defines methods (functions) Can call methods on itself and other objects
Memory allocation No memory allocated when class is defined Memory allocated when object is created
Creation Defined using the class keyword Created using the new keyword
Reusability Reusable - can create multiple objects Not directly reusable - represents a single entity

Example:

public class Car { // Class definition (blueprint)
  String color;
  int speed;

  public void accelerate() {
    speed++;
  }
}

Car myCar = new Car(); // Object creation (instance)
myCar.color = "Red";
myCar.accelerate();
System.out.println("Car color: " + myCar.color + ", Speed: " + myCar.speed);

In this example:

  • The Car class defines the properties (color and speed) and a method (accelerate) that all Car objects will have.
  • The myCar object is an instance of the Car class. It has its own specific color ("Red") and speed (initially 0).
  • We can call the accelerate method on myCar to modify its speed.

By understanding the distinction between classes and objects, you can effectively structure your Java programs and create objects that represent real-world entities or concepts.

Class vs Abstract class vs interface

Here's a breakdown of the key differences between classes, abstract classes, and interfaces in Java:

Class:

  • A fundamental blueprint for creating objects.
  • Defines both properties (variables) and behavior (methods) of the objects.
  • Can be directly instantiated (using new) to create objects.
  • Provides a complete implementation for its functionalities.

Abstract Class:

  • Acts as a template for subclasses and cannot be directly instantiated.
  • Defines a common structure and behavior for related classes.
  • Can have abstract methods (without a body) that subclasses must implement.
  • Enforces consistency and ensures subclasses provide required functionality.
  • May also have concrete (implemented) methods that can be reused by subclasses.

Interface:

  • Similar to an abstract class, but defines only abstract methods (no implementation).
  • Acts as a contract that specifies what functionality a class must provide.
  • A class can implement multiple interfaces, inheriting the required methods from each.
  • Focuses on what a class can do, not how it does it (implementation details are left to the class).

Here's a table summarizing the key points:

Feature Class Abstract Class Interface
Instantiation Can be directly instantiated (using new) Cannot be directly instantiated Cannot be directly instantiated
Abstract methods No (all methods must be implemented) Can have abstract methods (without a body) Only abstract methods (no implementation)
Concrete methods Can have concrete methods (with body) Can have concrete methods (with body) No concrete methods (only abstract methods)
Inheritance Can be inherited from Can be inherited from (but cannot be instantiated) Can be implemented by multiple classes
Implementation details Can have full implementation details Can have partial implementation details No implementation details (only method declarations)
Example Car, Employee Animal (abstract methods like makeSound()) Shape (abstract methods like calculateArea())

Choosing the Right Approach:

  • Use a class when you have a complete and concrete definition of an object with its properties and behavior.
  • Use an abstract class when you want to define a common structure and behavior for related classes, enforcing certain functionalities through abstract methods.
  • Use an interface when you want to specify a contract (what functionalities a class must provide) for achieving a specific behavior, allowing for different implementations in different classes.

By understanding these differences, you can effectively model real-world entities and their relationships in your Java programs using classes, abstract classes, and interfaces.

Interface vs Abstract class

Here's a breakdown of when to use interfaces and abstract classes in Java, along with examples:

When to Use Interfaces:

  • Standardizing behavior: Use interfaces when you want to define a set of methods that multiple unrelated classes can implement in different ways. This promotes code reusability and ensures consistency in functionality across different implementations.

Example:

public interface Shape {
  double calculateArea();
}

public class Circle implements Shape {
  double radius;

  @Override
  public double calculateArea() {
    return Math.PI * radius * radius;
  }
}

public class Square implements Shape {
  double side;

  @Override
  public double calculateArea() {
    return side * side;
  }
}

In this example, the Shape interface defines a single method calculateArea(). Both Circle and Square classes implement this interface, providing their own implementations for calculating area based on their specific shapes.

  • Achieving loose coupling: Interfaces promote loose coupling between classes. A class that uses an interface doesn't care about the specific implementation details. It just relies on the fact that any class implementing the interface will provide the required methods. This improves maintainability and testability.

Example:

public interface DatabaseConnection {
  void connect();
  void disconnect();
  void executeQuery(String query);
}

public class MySQLConnection implements DatabaseConnection {
  // Specific implementation for connecting to a MySQL database
  @Override
  public void connect() { ... }
  @Override
  public void disconnect() { ... }
  @Override
  public void executeQuery(String query) { ... }
}

public class OracleConnection implements DatabaseConnection {
  // Specific implementation for connecting to an Oracle database
  @Override
  public void connect() { ... }
  @Override
  public void disconnect() { ... }
  @Override
  public void executeQuery(String query) { ... }
}

The DatabaseConnection interface defines methods for database interactions. Both MySQLConnection and OracleConnection implement this interface, but their specific implementation details for connecting and querying data might differ. This allows switching between database implementations without modifying the code that uses the interface.

When to Use Abstract Classes:

  • Modeling inheritance and partial implementation: Use abstract classes when you have a set of related classes with a common structure and behavior. The abstract class can define some common methods and properties, while subclasses can extend and potentially override these methods to provide specific implementations.

Example:

public abstract class Animal {
  public abstract void makeSound(); // Abstract method

  public void sleep() {
    System.out.println("Animal is sleeping...");
  }
}

public class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Woof!");
  }
}

public class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow!");
  }
}

The Animal abstract class defines a common makeSound method (abstract) and a sleep method (concrete). Both Dog and Cat classes extend Animal and implement the makeSound method to provide their specific sounds, while inheriting the sleep behavior.

  • Enforcing specific behavior in subclasses: Abstract classes can enforce certain behavior in subclasses by declaring abstract methods that must be implemented. This ensures consistency within the related classes.

Key Points:

  • Interfaces focus on "what" functionalities a class should provide, while abstract classes can provide some "how" through concrete methods.
  • Interfaces promote multiple inheritance, while abstract classes follow a single inheritance hierarchy.
  • Use interfaces for behavior contracts, and abstract classes for defining a common foundation with partial implementation for related classes.