Can an implemented class have methods NOT declared in its parent interface?

梦想的初衷 提交于 2019-12-23 06:08:00

问题


I tried this in Eclipse and it shows a compile error. However trying the same in the online IDE Compilr showed no errors. That's why the confusion.

interface Iclass{
  void print();
  void hey();
}

class sdlfkajl implements Iclass {
  public void print(){
    System.out.println("Impl class");
  }
  public void  hey(){
    System.out.println("Hey!");
  }
  public void extra(){
    System.out.println("Should I be here?");
  }
}

The error shown is that this class cannot have methods not declared in the interface. Suggestion tooltip said I should declare this method in the interface too.


回答1:


There is no error in your code.

You might be mistaking a warning for an error - IntelliJ can be set to flag the code above as a warning.

You might also have a setting for warnings to fail the compile.

So check your IDE settings!




回答2:


Can an implemented class have methods NOT declared in its parent interface?

Yes it can.

I don't know what the problem is in your case, but it is not this.




回答3:


I don't know what error you got, but you are allowed to add additional methods to the implementation of an interface.




回答4:


An implemented class can of course have methods NOT declared in its interface. But is bound to implement methods which are declared in the interface unless it is declared abstract.




回答5:


The only error I can see you getting is if your interface and your implementation are in different package. Your interface has default visibility (aka "package private") which means it can only be seen (and used) within the same package. Try declaring your interface as public instead

public interface Iclass {
}

Other than that, having methods in a class that are not specified in the interface is perfectly legal in Java. The interface is the contract, the methods you MUST implement. It's not limited to ONLY those though.




回答6:


I tried to reproduce the same scenario but it works fine at my end.Try to clean the code, may this works. May be this would be a interface visibility issue




回答7:


You are allowed to add methods in a class that aren't declared in that class's interface.

I use Eclipse regularly and I think the problem you're running into has to deal with Eclipse itself rather than your code. Sometimes when you change and save the interface, Eclipse will display an error at the line where the change was made.

Try deleting the entire changed method and either retyping or pasting the code back in place. This should make Eclipse refresh the relevant work space and remove the error.



来源:https://stackoverflow.com/questions/9715574/can-an-implemented-class-have-methods-not-declared-in-its-parent-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!