以下接口有什么(如果有的话)是错误的?这个接口有什么问题?
public interface WorldsBestInterface {
void favoriteMethod(int greatValue){
System.out.println("Thanks for the smile");
}
}
我有一个问题解决这个问题。
以下接口有什么(如果有的话)是错误的?这个接口有什么问题?
public interface WorldsBestInterface {
void favoriteMethod(int greatValue){
System.out.println("Thanks for the smile");
}
}
我有一个问题解决这个问题。
不应该包含实现。接口只包含方法声明,它不包含实现。
void favoriteMethod(int greatValue){
System.out.println("Thanks for the smile");
}
应该
public interface WorldsBestInterface {
void favoriteMethod(int greatValue);
}
对!谢谢。我知道这是接口的规则之一。 – TheMogul 2012-07-19 15:57:55
接口没有任何代码在其中,只是签名。
public interface WorldsBestInterface {
void favoriteMethod(int greatValue);
}
你应该有
public interface WorldsBestInterface {
void favoriteMethod(int greatValue); // no body, just declaration
}
正如其他人所说,接口只定义一个类的结构。这是一个实现它的类的合约,如果你选择使用它,那么你也必须包含这里定义的方法。所以实现它的任何类都保证有接口。
如果您需要在方法中使用代码,则替代此方法将是一个抽象类。然后,您必须将其子类化才能使其可用。
在接口的情况下,我们只提供方法签名。但是,如果存在某些方法需要具体实现的情况,而其他方法只需要方法签名,则可以考虑使用创建抽象类的方法。例如
public abstract class WorldsBestAbstractClass{
public void favoriteMethod(int greatValue){
System.out.println("Thanks for the smile");
}
public abstract void nextFavoriteMethod(int smallValue);
}
只是尝试编译它,你会发现! – 2012-07-19 15:58:31
这只是显示你在课堂上没有多加关注,甚至没有尝试过使用[Java中的接口]搜索(http://docs.oracle.com/javase/tutorial/java/concepts/interface.html )。 – 2012-07-19 16:03:13
-1 plz你做作业 – maasg 2012-07-19 16:26:45