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.
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.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.