interface vs abstract class java

http‮/:s‬/www.lautturi.com
interface vs abstract class java

In Java, an interface is a collection of abstract methods that a class can implement. An abstract class is a class that can contain both abstract methods (methods without a body) and concrete methods (methods with a body).

Some key differences between interfaces and abstract classes in Java include:

  • Interfaces can only contain abstract methods, while abstract classes can contain both abstract and concrete methods.
  • A class can implement multiple interfaces, but it can only extend a single abstract class.
  • An interface cannot have any implementation code, while an abstract class can have code that is shared by its subclasses.
  • Interfaces are more flexible, as they allow you to specify common behavior that can be implemented by any class, regardless of its inheritance hierarchy. Abstract classes, on the other hand, are more useful for defining common implementation code that can be shared among subclasses.

Here is an example of an interface in Java:

public interface Shape {
  double getArea();
  double getPerimeter();
}

And here is an example of an abstract class in Java:

public abstract class Animal {
  private String name;
  private int age;

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

  public abstract void makeSound();
  
  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }
}

In this example, the Shape interface defines two abstract methods that calculate the area and perimeter of a shape. The Animal abstract class defines an abstract method makeSound that represents the sound an animal makes, as well as concrete methods getName and getAge that return the name and age of the animal.

For more information on interfaces and abstract classes in Java, you can refer to the Java documentation.

Created Time:2017-11-01 22:29:53  Author:lautturi