当您覆盖方法时,您不能降低继承方法的可见性。根据下表,protected比nomodifier更易于访问:|Class|Package|Subclass|World————————————+———————+—————————+——————————+———————public|y|y|y|y————————————+———————+—————————+——————————+———————protected|y|y|y|n————————————+———————+—————————+——————————+———————nomodifier|y|y|n|n————————————+—————
程序一classB{publicvoidm1(intx){System.out.println("Superclass");}}classAextendsB{publicvoidm1(int...x){System.out.println("Subclass");}}classtest1{publicstaticvoidmain(Stringargs[]){Bb1=newB();b1.m1(10);Aa=newA();a.m1(10);Bb2=newA();b2.m1(10);}}输出:super类父类(superclass)(无法理解为什么父类(superclass)?!)父类(su
我知道如何重载方法,以及如何覆盖方法。但是有可能同时重载和覆盖一个方法吗?如果是,请举例说明。 最佳答案 重载和覆盖是互补的东西,重载是方法名相同但参数不同,覆盖是子类中方法名相同,参数相同。所以不可能同时发生重载和覆盖,因为重载意味着不同的参数。例子:classA{publicvoiddoSth(){///}}classBextendsA{publicvoiddoSth(){/*methodoverriden*/}publicvoiddoSth(Stringb){/*methodoverloaded*/}}干杯!
这个问题在这里已经有了答案:关闭12年前。PossibleDuplicate:What's“@Override”thereforinjava?到目前为止,我从未在方法前放置“@Override”。我看到了一些代码示例,但我不明白它的实用性。我想要一些解释。非常感谢,JDelage
我有几个接口(interface):publicinterfaceEndpoint{publicClassgetFetchableType();}publicinterfaceFetchable{...fetcheddatafields}publicinterfaceFetcher{publicTfetch(Endpointendpoint);}对于实现Fetcher的类,为什么编译器使用这个方法声明:publicFetchableImplfetch(Endpointendpoint){returnnull;}虽然这些都是不正确的声明:publicFetchableImplfetch(
回答这个问题:HowtoGUI-Usingpaintcomponent()toinitializeaGUIandthentoaddGUIbasedonmouse我已经声明了:Youdon'toverridepaintComponent()properly.Thisisaprotectedmethod,notpublic.Ifyouadd@Overrideannotationonthismethodthenthecompilerwillcomplain.但是@peeskillet明智地指出了这一点:Thecompilerwillnotcomplainaboutpublicorprotec
所以我之前问过这个问题,但大多数人发现我的代码有错误,而不是问题本身。无论如何,我正在尝试重写类中的接口(interface)方法。但是,我希望覆盖方法中的参数类型是覆盖方法中定义的参数类型的子类。界面是:publicinterfaceObserver{publicvoidupdate(ComponentUpdateEventupdateEvent)throwsException;}虽然重写这个方法的类是:publicclassConsoleDrawerextendsDrawer{//...@Overridepublicvoidupdate(ConsoleUpdateEventupda
请考虑以下代码:classA{publicstaticvoidm(Numbern){System.out.println("NumberA");};}classBextendsA{publicstaticintm(Numbern){System.out.println("NumberB");return1;};}输出:java:m(java.lang.Number)ininheritanceTest.Bcannotoverridem(java.lang.Number)ininheritanceTest.Areturntypeintisnotcompatiblewithvoid我知道静态
我知道main()可以在一个类中重载,编译器总是将带有String[]args的参数作为执行开始的主要方法。但是是否可以声明相同的main(Stringargs[])inaninterfaceandimplementitindifferentclassesdifferently?例如,packagetest;interfacetest{publicvoidmain(Stringargs[]);publicvoiddisplay();}packagetest;classTestclass1implementstest{publicvoiddisplay(){System.out.prin
下面是书中的引述:TheoverridingmethodmustNOTthrowcheckedexceptionsthatareneworbroaderthanthosedeclaredbytheoverriddenmethod.Forexample,amethodthatdeclaresaFileNotFoundExceptioncannotbeoverriddenbyamethodthatdeclaresaSQLException,Exception,oranyothernon-runtimeexceptionunlessit'sasubclassofFileNotFoundExc