Difference Between Class And Interface In Java

In Java, while classes and interfaces may appear similar in syntax, they differ in several aspects. Both classes and interfaces can contain methods, variables, and constants. The following section will elaborate on the distinctions between classes and interfaces.

What is a Class?

A class serves as a template for generating instances, encompassing attributes and functions that specify the characteristics and actions of instances.

Example of a Class

Example

class Animal {

    String name; // Instance variable

void makeSound() {

        System.out.println("Animal makes a sound");

    }

}

In this scenario, the class Animal contains an attribute named 'name' and a function named 'makeSound'.

Advantages of Using Classes

  • Encapsulation: A class groups related data and methods together, preventing direct access and ensuring better data security.
  • Reusability: With inheritance , a class can be extended to add new features without modifying the original code.
  • Flexibility: Polymorphism allows objects to take different forms, making code more adaptable and easier to manage.
  • What is an Interface?

An interface serves as an agreement outlining a collection of methods that a class is required to execute. It does not include any concrete method implementations, except for certain exceptional scenarios.

Example of an Interface

Example

interface Animal {

    void makeSound(); // Abstract method (no body)

}

In this context, an interface called Animal is defined to specify a method without implementing its functionality.

Advantages of Using Interfaces

  • Loose Coupling: Interfaces reduce dependencies, making it easier to modify or replace components without affecting the entire system.
  • Multiple Inheritance: A class can implement multiple interfaces, overcoming Java’s single inheritance limitation.
  • Testability: Interfaces simplify unit testing by allowing mock implementations, making testing more efficient and isolated.
  • When to Use a Class or Interface?

  • Use a class when we want to define real-world objects with properties and behaviours.
  • Use an interface when we want to enforce rules that multiple classes must follow.
  • Java Class Vs. Interface

Feature Class Interface
Methods It can have both normal and abstract methods. It can only have abstract methods (before Java 8). Default and static methods are allowed from Java 8.
Variables It Can have any type of variable. It Can only have final and static variables.
Inheritance A class can extend another class (single inheritance). An interface can extend multiple interfaces (multiple inheritance).
Implementation A class can implement an interface using implements. An interface cannot implement another interface, only extend it.
Constructors It can haveconstructors. It cannot have constructors.
Instantiation A class can be instantiated, i.e., objects of a class can be created. An interface cannot be instantiated directly; instead, it is implemented by a class or a struct.
Multiple Inheritance Not supported for classes. Supported using multiple interfaces.
Access Modifiers It can have any access modifiers (public, private, protected, default). Methods are public by default. Private methods allowed from Java 9.
Usage It is used to define the state and behaviour of objects. It is used to define a contract that multiple classes follow.

Example of Class and Interface

File Name: Main.java

Example

Example

interface Animal {

    void makeSound(); // Abstract method

}

class Dog implements Animal {

    public void makeSound() {

        System.out.println("Dog barks");

    }

}

class Cat implements Animal {

    public void makeSound() {

        System.out.println("Cat meows");

    }

}

public class Main {

    public static void main(String[] args) {

        Animal dog = new Dog();

        Animal cat = new Cat();

        dog.makeSound(); // Output: Dog barks

        cat.makeSound(); // Output: Cat meows

    }

}

Output:

Output

Dog barks

Cat meows

Explanation

The Animal interface in this instance enforces that any class that implements it must explicitly declare the makeSound method. Both the Dog and Cat classes adhere to this requirement by offering their own implementations: one outputs "Dog barks," while the other displays "Cat meows." Within the Main class, instances of Dog and Cat are instantiated and assigned to the Animal data type. As makeSound is invoked, Java dynamically identifies and executes the appropriate method for each instance.

Conclusion

Classes and interfaces play crucial roles in Java programming, each with distinct functions. Classes are responsible for defining concrete objects, whereas interfaces set up a set of rules that can be followed by multiple classes. Recognizing the variances between these two concepts is valuable when creating resilient and expandable software solutions.

Input Required

This code uses input(). Please provide values below: