Difference between abstract class and interface

Difference between abstract class and interface

Difference between abstract class and interface

Difference between abstract class and interface:

In Java, an abstract class and an interface are two different constructs that are used to define abstract behavior, but they have some key differences.

  1. Method implementation: An abstract class can have both abstract and non-abstract methods, which means it can provide a partial implementation of the interface. An interface, on the other hand, can only declare abstract methods, which must be implemented by any class that implements the interface.
  2. Inheritance: A class can extend only one abstract class, whereas a class can implement multiple interfaces. This is because Java supports single inheritance but multiple interface implementation.
  3. Access modifiers: An abstract class can have any access modifier, whereas an interface can only have public access modifier for its methods and variables.
  4. Variables: An abstract class can have instance variables, whereas an interface can only have constant variables (i.e., static final variables).
  5. Constructors: An abstract class can have constructors, whereas an interface cannot have constructors.
  6. Purpose: An abstract class is usually used to define common behavior among a group of related classes, while an interface is used to define a contract that a class must follow in order to be used in a particular context.

Here’s an example to illustrate the difference:

				
					public abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
System.out.println(name + " is eating");
    }

    public abstract void makeSound();
}

public interface Pet {
    void play();
}

public class Dog extends Animal implements Pet {
    public Dog(String name) {
        super(name);
    }

    @Override
    public void makeSound() {
System.out.println("Bark!");
    }

    @Override
    public void play() {
System.out.println("Fetch!");
    }
}

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

				
			

In the example above, Animal is an abstract class that defines a common eat() method and an abstract makeSound() method. Pet is an interface that defines a play() method. Dog is a class that extends Animal and implements Pet, providing implementations for all the abstract methods. The Main class creates an instance of Dog and calls its methods.

Join To Get Our Newsletter
Spread the love