Abstract class vs Interface
Abstract class
- An abstract class is a class that is declared with 'abstract' keyword
- It may or may not include abstract methods
- An abstract class cannot be instantiated.
- An abstract class can implement interface without even providing the implementation of interface methods.
Syntax
abstract class Payment
{
//constants and methods
}
Example
abstract class Payment
{
abstract void doPayment();
{
abstract void doPayment();
}
class CreditCardPayment extends Payment
{
{
@Override
void doPayment()
{
Sysout("Payment with CreditCard");
}
}
Interface
- Interface is the way to achieve abstraction in Java.
- 'Interface' keyword is used to create Interface.
- Just like Abstract class Interface also cannot be instantiated.
- All the fields declared in interface are public, static and final by default.
- All the methods declared in interface are public and abstract by default.
- You can also create concrete method using 'default' keyword (introduced in Java8).
- You can also create class inside Interface.
Syntax
interface Payment
{
//constants
//abstract methods
//concrete methods (introduced in Java8) using 'default'
}
Example
interface Payment
{
//constants
String type= "PAYMENT";
//abstract method
void doPayment();
//concrete method
default void printMessage() { System.out.println();
}
}
public class CreditCard implements Payment
{
@Override
public void doPayment() {
System.out.println("value is : "+ type);
}
public static void main(String[] args){
final CreditCard creditCard = new CreditCard();
creditCard.doPayment();
creditCard.printMessage();
}
}
*printMessage() is default method, creating a concrete method in interface is possible with Java 8
Which should we use, abstract class or interface?
<< If you want to use abstract class >>
- Basically abstract class should be used with closely related classes, for example
- "Animal" is abstract class Then its subclasses should be Lion, Tiger, Fox etc.
- "Shape" is abstract class Then its subclasses should be circle, triangle, rectangle etc
- When you expect that subclass has no other class to extend
- When you want to declare non-static or non-final fields.
<< If you want to use Interface >>
- You expect that unrelated classes would implement your interface.
- You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
- You want to take advantage of multiple inheritance of type.
- Examples - Cloneable, Comparable, Comparator
========================Thank You============================
Comments
Post a Comment