问题
Here is the code I'm having problems with:
The interface:
public interface anInterface {
void printSomething();
}
Class that implements the interface:
public class aClass implements anInterface {
public aClass() {
}
public void printSomethingElse() {
System.out.println("Something else");
}
@Override
public void printSomething() {
System.out.println("Something");
}
}
And the main function:
public static void main(String[] args) {
anInterface object = new aClass();
object.printSomething(); // works fine
object.printSomethingElse(); // error
}
Error: Cannot find symbol. Symbol: method printSomethingElse();
Can anybody tell me why this won't work?
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?
I have also tried it in C# and doesn't work either.
What am I doing wrong?
Thanks!!!
回答1:
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.
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.
来源:https://stackoverflow.com/questions/10068263/why-wont-my-interface-typed-objects-preform-methods-that-are-not-declared-in-th