n00b
n00b

Reputation: 214

Java Interfaces and inheritance

I have a very basic doubt about Java Interfaces and inheritance. Suppose I have two classes A and B and one interface C with following definitions

interface C{
 public void check();
}

class A implements C{
 public void check(){
  System.out.println("A");
 }
}

class B extends A implements C{

// Is the following method overriding the method from class A or implementing the method from C?
 public void check(){
  System.out.println("B");
 }

}

I am confused that whether it is over-riding or implementation of check() method in class B?

Upvotes: 1

Views: 131

Answers (4)

Will.O
Will.O

Reputation: 59

In your example:

class B extends A implements C{

// Is the following method overriding the method from class A or implementing the method from C?
 public void check(){
  System.out.println("B");
 }

}

You are defining the check method in interface C as:

 public void check(){
  System.out.println("B");

You are allowed to do this as interfaces don't contain the definition of the method in the interface when they are created and can thus be used over and over again for things which are similar enough to use the same method with a few tweaks.

Upvotes: 0

dimitrisli
dimitrisli

Reputation: 21391

As @Jeroen Vannevel and @EJP have mentioned above it's both overriding and implementing.

In order to understand this I think you need to see it in the context of compile/run time.

You have the following possible scenarios:

C c = new B();
c.check();

At compile-time you see C#check() (you can use your IDE to get you where c.check() points to) at runtime you see the overridden B#check()

A a = new B();
a.check();

At compile-time you see A#check() (you can use your IDE to get you where c.check() points to) at runtime you see the overridden B#check()

B b = new B();
b.check();

At compile-time you see B#check() (you can use your IDE to get you where c.check() points to) at runtime you see the overridden B#check()

If alternatively you are passing the method call directly in a method:

someMethod(new B().check())

then this equates the last of the above scenarios

Upvotes: 3

user207421
user207421

Reputation: 310903

It is both over-riding and implementing.

Upvotes: 2

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

It does both, they are not mutually exclusive. The purpose of an interface is to define a method signature that should be available inside the implementing class.

You should annotate the method with @Override though, it's just good form because it makes clear that it comes from a baseclass and it'll guard you against accidental typos.

Upvotes: 8

Related Questions