Hedayat Mahdipour
Hedayat Mahdipour

Reputation: 183

Methods with the same name in java

Suppose we have an interface such as the following in java

public interface AnInterface
{
      public void aMethod();
}

and a class as follows:

public class AClass
{
   public void aMethod()
   {
      //bla bla bla
   }
}

Now I'm going to define another class such as Subclass that extends AClass and implements AnInterface, as in:

public class Subclass extends AClass implements AnInterface
{
   public void aMethod()
   {
      //do something
   }
}

What does exactly aMethod() do in Subclass? Does it implement the method in AnInterface? Or does it overrides the method in AClass?

What should I do in order to make aMethod() implement the method of AnInterface? Similarly, if I want it to override the method in AClass, what can I do with it?

Upvotes: 0

Views: 84

Answers (1)

Jonas Lomholdt
Jonas Lomholdt

Reputation: 1590

As you might have noticed, the interface method(s) does not have any body. This simply means, that a class implementing this interface must implement those methods, here aMethod(). Your class SubClass extends AClass and inherits the method aMethod() from it. Now implementing the aMethod in the SubClass will simply override the method from AClass and at the same time adhere to the interface rules. So the method in effect will be the one in the SubClass.

To answer your question in short: The aMethod() in Subclass currently both implements the method from AnInterface AND overrides it from AClass.

Upvotes: 1

Related Questions