- Explain the difference between an interface and a abstract class?
Abstract class: Is a superclass that cannot be instantiated and is used to state or define general characteristics. An object cannot be created from a Java abstract class. The abstract class is declared using the keyword abstract. Subclasses extended from an abstract class have all the abstract class’s attributes.
Interface: is a blueprint of a class. It has static constants and abstract methods. There can only be abstract methods in the Java interface, not method body. The interface is declared using the keyword implements.
| Abstract Class | Interface |
| Can extend another java class and implement multiple java interfaces. | Can extend only java interfaces. |
| Can have a constructor | Can’t have a constructor. |
| Can have both abstract and concrete methods. | Can only have abstract methods. |
| Can have final, non final, static and non static variables. | Can only have static and final variables. |
For more information on Abstract class and Interface click on the hyperlink.
2) What is Polymorphism?
Polymorphism: is the ability of a method to do different things based on the object that it is acting upon. In other words is a feature that allows us to perform a single action in different ways.
Lets write an example:
class Animal{
public void sound(){
System.out.println("Animal is making a sound");
}
}
public class Cat extends Animal{
@Override
public void sound(){
System.out.println("Meaow");
}
public static void main(String args[]){
Cat cat = new Cat();
cat.sound();
}
}
The output of this code will be “Meaow”.
In the class Cat there is the syntax @Override. This tells the compiler that you intend to override the method from the superclass. The word extends is what allows the class Cat to inherit the Animal class methods.
For more information on polymorphism you can click here.
If you have any questions feel free to leave a comment.