问题描述
这是我遇到问题的代码:
Here is the code I'm having problems with:
界面:
public interface anInterface {
void printSomething();
}
实现该接口的类:
public class aClass implements anInterface {
public aClass() {
}
public void printSomethingElse() {
System.out.println("Something else");
}
@Override
public void printSomething() {
System.out.println("Something");
}
}
主要功能:
public static void main(String[] args) {
anInterface object = new aClass();
object.printSomething(); // works fine
object.printSomethingElse(); // error
}
错误:找不到符号.符号:方法printSomethingElse();
Error: Cannot find symbol.Symbol: method printSomethingElse();
有人可以告诉我为什么这行不通吗?
Can anybody tell me why this won't work?
在Java中,当您有一个实现某些接口的类时,即使未在接口中声明这些方法,也可以向该类添加方法吗?还是我必须声明将在接口中使用的所有方法?
Is it possible in Java, when you have a class that implements some interface, to add methods to that class, even though those methods have not been declared in the interface? Or do I have to declare ALL the methods that I will be using in the interface?
我也曾在C#中尝试过它,也无法正常工作.
I have also tried it in C# and doesn't work either.
我在做什么错了?
谢谢!
推荐答案
您必须在接口中声明要在这种情况下使用的所有方法.该界面对printSomethingElse一无所知,这就是为什么您遇到上述错误的原因.
You have to declare all methods that you want to use in that case in the interface. The interface knows nothing of printSomethingElse and that is why you're getting the above error.
接口的目的是使您可以在多个相似的已实现类之间拥有通用的功能列表.例如,List
是一个接口,其中包含由不同类以各种方式实现的功能的列表",例如,LinkedList
使用双向链接列表来提供List
和ArrayList
的功能,动态扩展数组可以做到这一点.
The purpose of an Interface is so that you can have a common list of functions across multiple similar implemented classes. For example, List
is an interface which contains a 'list' of functions implemented in various ways by different classes such as LinkedList
which uses a Doubly Linked list to provide the functionality of List
and ArrayList
which uses an Dynamically expanding array to do so.
这篇关于为什么我的接口类型对象不能执行未在接口中声明的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!