Why won't my interface typed objects preform methods that are not declared in the interface?

五迷三道 提交于 2019-12-12 03:08:47

问题


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

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