Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened when subclass and superclass both implement a same interface

Tags:

java

oop

interface Vehicle
{   
    public abstract void getVehicle();      
}

public class HelloWorld  implements Vehicle{
@Override
public void getVehicle() 
 {
    System.out.println("HelloWorld Implementation");        
 }
}

class MyWorld extends HelloWorld implements Vehicle
{       
@Override
public void getVehicle() 
 {
    System.out.println("MyWorld Implementation");       
 }   
}

When Both Classes are Implementing the abstract method getVehicle(), what is actually happening here ? Is the sub-class overriding super-class getvehicle() , or Inteface getVehicle() ?

like image 932
Chanky Mallick Avatar asked Mar 16 '23 12:03

Chanky Mallick


2 Answers

The sub-class's implementation would override the super-class's implementation. There's no meaning to saying the sub-class would override the interface's method, since the interface doesn't supply an implementation (unless you are talking about Java 8 default interface methods).

BTW, it's enough to declare that the super-class implements the interface. The sub-class would implement it implicitly without declaring that it implements it.

So even if you write :

public class HelloWorld implements Vehicle

and

class MyWorld extends HelloWorld

MyWorld still implements Vehicle.

like image 154
Eran Avatar answered Apr 07 '23 09:04

Eran


  • The interface defines "What methods should be there"
  • The parent class defines the method
  • The child class defines and overrides the method defined in the parent class

So, it would behave just like any other inheritance

(even if the default method implementation is available in interface [Java 8])

Although, implementing the interface in the child class (when the parent already implements the same interface) has no impact on behavior. Doing so helps improve readability in some cases.

like image 32
Mohit Kanwar Avatar answered Apr 07 '23 09:04

Mohit Kanwar