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:
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.