Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of interfaces and abstract classes? [duplicate]

Possible Duplicates:
purpose of interface in classes
What is the difference between an interface and abstract class?

Hi I am a php programmer. any body can explain what is the advantage of using interface and abstract class.

like image 213
DEVOPS Avatar asked Jan 05 '11 17:01

DEVOPS


People also ask

Why do we need both interface and abstract classes?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

What are the advantages of interfaces?

Interfaces support Multiple Inheritance (MI) very effectively and efficiently. If required, interfaces can form complex MI hierarchies. Also a class can support hundreds of interfaces without any negative impact on performance.

Why interfaces If abstract classes are already there?

Interfaces are more flexible, because a class can implement multiple interfaces. Since Java does not have multiple inheritance, using abstract classes prevents your users from using any other class hierarchy. In general, prefer interfaces when there are no default implementations or state.

What are the similarities of abstract classes and interfaces?

Both Interfaces and Abstract Classes can have methods and variables, but neither of them can be instantiated. All the variables declared within the interface are final. However, the variables declared in Abstract Classes can be non-final and can be modified by the user-defined classes.


1 Answers

The main advantage of an interface is that it allows you to define a protocol to be implemented for an object to have some behavior. For example, you could have a Comparable interface with a compare method for classes to implement, and every class that implements it would have a standardized method for comparison.

Abstract classes allow you to define a common base for several concrete classes. For example, let's say you wanted to define classes representing animals:

abstract class Animal {
    abstract protected function eat();
    abstract protected function sleep();
    public function die() {
        // Do something to indicate dying
    }
}

In this case, we define eat() and sleep() as abstract because different types of animals (e.g. lion, bear, etc.) that will inherit from Animal eat and sleep in different ways. But all animals die the same way (don't hold me to that), so we can define a common function for that. Using an abstract class helped us 1.) declare some common methods that all Animals should have, and 2.) define common behavior for Animals. So, when you extend Animal, you won't have to rewrite the code for die().

like image 155
Rafe Kettler Avatar answered Nov 03 '22 01:11

Rafe Kettler