1

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?

1
  • 3
    It's both. Method check in B implements the method in interface C but it overrides the existing implementation in superclass A. Commented Oct 29, 2014 at 8:14

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

It is both over-riding and implementing.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.