[英]Java :Interface Method's Overriding
package chap8;
interface Interfaces
{
void nMethod(); // normal method of interface
default void dMethod() // default method of interface
{ System.out.println("Default Method of Interface"); }
static void sMethod() // static method of interface
{ System.out.println(" static method of interface"); }
}
class IClass implements Interfaces
{
public void nMethod()
{ System.out.println("Normal Method of Interface in IClass ");}
static void sMethod()
{ System.out.println("Does function overrided ?");}
public void dMethod()
{ System.out.println("default Method of Interface in IClass ");}
}
class MainClass
{
public static void main(String args[])
{
IClass ob =new IClass();
ob.nMethod();
ob.sMethod(); // overrided method ??
ob.dMethod();
// calling static
//Interfaces.sMethod // via Interfaces
// IClass.sMethod(); // via IClass (why all these sMethod calling showing error)
}
}
問題:a)接口中聲明的sMethod是否被IClass中存在的sMethod覆蓋?
b)為什么我不能通過接口和IClass調用sMethod?
THPR FPR的幫助!
有關默認方法和靜態方法,請參考oracle文檔。
擴展包含默認方法的接口
擴展包含默認方法的接口時,可以執行以下操作:
關於您的查詢:
dMethod
overridden
IClass
sMethod()
中IClass
隱藏sMethod()
在Interfaces
簡化您的例子
public class A {
interface I {
static void sMethod() {
System.out.println("In the interface I");
}
}
static class C implements I {
void sMethod() {
System.out.println("In the class C");
}
}
public static void main(String[] args) {
I.sMethod();
new C().sMethod();
}
}
版畫
In the interface I
In the class C
IClass中是否存在被sMethod覆蓋的接口中聲明的sMethod?
static
方法是隱藏的,而不是被覆蓋。 這意味着在特定的類上調用靜態方法,您將始終獲得比方法更多的信息,因為它將不遵循繼承,並為您提供了一個被重寫的方法(實際上,它不能,因為它不使用實例)
為什么我無法通過Interface和IClass調用sMethod?
我不清楚,請參見上面的示例,其中的單詞符合預期。
您不能再打電話給他們。
澄清@Hulk的評論。 您不能通過實例調用它們,但是可以通過實現它們的class
或interface
來調用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.