what is the actual use of interface in java?
Solution 1
What you like : thousands of abstract methods in one Abstract Class and inherit this class OR make as many interfaces for specific abstract methods and use those only you want by inheriting as many interfaces as needed...
abstract class A
{
//thousands of abstract method();
abstract methodA();
abstract methodB();
abstract methodC();
}
//OR
interface ForOnlymethodA
{
void methodA();
}
interface FormethodBandmethodC
{
void methodB();
void methodC();
}
So, use that method only what you just need by inheriting particular interface, if you are inheriting Abstract
classes then you are unnecessarily inheriting all methods that you don't need in one class and may be needed in some other classes..
Solution 2
Interfaces allow you to use classes in different hierarchies, polymorphically.
For example, say you have the following interface:
public interface Movable {
void move();
}
Any number of classes, across class hierarchies could implement Movable
in their own specific way, yet still be used by some caller in a uniform way.
So if you have the following two classes:
public class Car extends Vehicle implements Movable {
public void move() {
//implement move, vroom, vroom!
}
}
public class Horse extends Animal implements Movable {
public void move() {
//implement move, neigh!
}
}
From the perspective of the caller, it's just a Movable
Movable movable = ...;
movable.move(); //who am I?
I hope this helps.
Solution 3
Multiple interfaces can be implemented, but only one class can be extended. A completely abstract class is a lot like an interface, except that an abstract class can contain variables.
It really depends on what you need. C++ allows you to extend as many classes you want, and it turns into a bit of a disaster. The nice thing about having only one superclass is that there's only ever one other set of implementations that you have to worry about (even if the parent has a parent, the parent's particular combination becomes your parent...)
Interfaces allow one object to play many roles, but they don't allow code reuse.
It's really to simplify thinking about inheritance. On the balance, I think they got it right.
Solution 4
Advantages over an abstract class? except the fact you can implement multiple interfaces but extend only one (abstract or not) class, it's the same as an abstract class that all of it's methods are abstract and public
Comments
-
kandarp almost 2 years
Possible Duplicates:
Abstract class and Interface class?
Java: interface / abstract classes / abstract methodIn Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?
-
kandarp over 13 yearsthanks to provide valuable information.
-
kandarp over 13 yearsthanks to help me to understand difference between interface and abstract with proper example.