简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM