Reputation: 417
Normal overriding (without the use of interfaces)
class A {
int x = 0;
void show() {
System.out.println("In A. x : " + x);
}
}
class B extends A {
void show() {
System.out.println("In B. x : " + x);
}
}
class C extends A {
void show() {
System.out.println("In C. x : " + x);
}
}
class Test {
public static void main(String args[]){
A obj = new B();
obj.show();
obj = new C();
obj.show();
}
}
This is the same as doing that with interfaces:
interface A {
int x = 0;
void show();
}
class B implements A {
public void show() {
System.out.println("In B. x : " + x);
}
}
class C implements A {
public void show() {
System.out.println("In C. x : " + x);
}
}
class Test {
public static void main(String args[]){
A obj = new B();
obj.show();
obj = new C();
obj.show();
}
}
Output in both the cases will be the same and even the implementation is similar. My question is, why have interfaces when you can do the same thing by using dynamic method dispatch?
Upvotes: 1
Views: 3829
Reputation: 148870
Interfaces and superclasses are for different use cases :
Interfaces are necessary when proxying, because a proxy can only implements interface and does not extends classes. And proxies are heavily used in a framework like Spring to have a simple Aspect Oriented Programming.
Upvotes: 1
Reputation: 4639
There are some points to consider for this :
I hope this will make you clear difference about both design.
Upvotes: 2
Reputation: 7863
Vikingsteve is right but I'll add a little more detail.
There is a difference between type inheritance and implementation inheritance. In Java you can have multiple type inheritance but not multiple implementation inheritance.
This means a class can implement multiple interface and inherits the type from each of those interfaces. An object created from that class is basically of all those types at once. But you can only extend one other class and inherit its implementation.
Upvotes: 1