Abstract Class VS Interface
To read about Interface click here
To read about Abstract Class click here
While creating
interface , you create it as interface. While creating abstract class, you
create it as regular class and later you convert it as an abstract class.
Abstract class
have keyword "abstract class" , Interface has keyword
"interface".
Abstract methods
inside Abstract class should use the keyword "abstract". Abstract
method inside interface may or may not use "abstract" keyword.
Access modifiers
for the interface variables and methods are by default public. It allows public
and default only.
Access modifiers
for an abstract class variables and methods are private(only non-abstract
methods and variables), public or protected.
Interface can
have only abstract methods.
Abstract class
can have both abstract and non-abstract methods and constructors.
The variables
values in interface are final by default.
The variables
values in abstract methods need not to be final.
An abstract class
can extend another abstract class or implement interface.
An interface can
not extend any classes. Interface can extend another interface or interfaces.
An abstract class
or normal class can not extend more than one abstract class or normal class ,
ie, does not support multiple inheritance.
An interface can
extend one or more interfaces. An abstract class or normal class can implements
one or more interfaces.
public interface InterfaceName extends Intf1, Intf2{
}
public class ClassName implements Intf1, Intf2 { //class or
abstract class
}
Speed wise
Interface is slow, Abstract class is fast.
Default access
modifier is possible only in interface. Because in an existing interface, the
abstract methods are already being implemented by implementing classes. So, if
you add any other regular abstract method, those implementing classes have to
implement them. To avoid this situation, we use default access modifier to
write new method in interface.
public interface InterfaceXYZ
{
default void red()
{
System.out.println("Default method in
interface");
}
Class
implementing the interface:
public class XYZ implements InterfaceXYZ{
public static void main(String[] args) {
XYZ xyz = new XYZ();
xyz.red();
}
Output:
Default
method in interface
Benefits of
Interface and Abstract Class :
Interface and
Abstract class are used mainly for security (hiding data/information). Other benefits
of using Abstract Class(AC) are : AC is faster, it allows different access
modifiers , it allows abstract and non-abstract methods, it can implements more
than one interfaces, variables could be final, non-final, static, non-static , initialized
, non-initialized , AC can have constructors.
Benefits of
Interface: Security, allows default access modifier , allows multiple
inheritance.
No comments:
Post a Comment