16. Can we create objects from abstract class and interface?

We can not create objects from abstract class or interface directly but we can create an instance of class implement that interface or extend that abstract class.
And because we have polymorphism pillar of OOP, so we can create reference variable has data type of that interface or abstract class

–> create an instance for that variable is an instance of class implement interface or extends from abstract method.

Example :

// Create an interface named AnimalActions
public interface AnimalActions {
void makeSound();
void move();
}

// Create a abstract class named Animal
public class Animal {
private String name;

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

public String getName() {
return name;
}

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

// The Dog class extends Animal and implements AnimalActions
public class Dog extends Animal implements AnimalActions {

public Dog(String name) {
super(name);
}

@Override
public void makeSound() {
System.out.println(getName() + ” says: Woof!”);
}

@Override
public void move() {
System.out.println(getName() + ” is running.”);
}
}

// The Cat class extends Animal and implements AnimalActions
public class Cat extends Animal implements AnimalActions {

public Cat(String name) {
super(name);
}

@Override
public void makeSound() {
System.out.println(getName() + ” says: Meow!”);
}

@Override
public void move() {
System.out.println(getName() + ” is jumping.”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *