Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why implement interfaces 'A' and 'B', when 'B' extends 'A'

Suppose I have the following code...

interface A{
  void a();
}

interface B extends A{
  void b();
}

class ImplementOne implements B{ 
  public void a(){};
  public void b(){};
}     

class ImplementTwo implements B, A{ 
  public void a(){};
  public void b(){};
} 

Regardless of whether class ImplementTwo implements both B and A, or just B, it would still need to implement method a() in interface A, since interface B extends interface A. Is there any reason one would explicitly do

...implements B, A

instead of just

...implements B  

?

like image 503
Skogen Avatar asked Dec 19 '22 11:12

Skogen


1 Answers

There is no difference between the two approaches in terms of behavior. In terms of bytecode information, there is a small difference when it comes to information about implemented interfaces. For example:

Class<?>[] interfaces = ImplementTwo.class.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
    System.out.println(interfaces[i]);
}

would return two class instances when implements B, A is used, whereas when using implements B it would return one instance.

Still, the following returns true using both approaches:

A.class.isAssignableFrom(ImplementTwo.class)
like image 126
M A Avatar answered Dec 28 '22 02:12

M A