簡體   English   中英

通過超類/接口引用進行引用-Java

[英]Referencing through super class/interface reference - Java

我是Java的新手,我了解繼承的基本基本概念。 我有一個關於通過超類進行引用的問題。 由於可以通過超類引用(接口或類)來引用從超類繼承或使用接口實現的類方法。 當一個類的擴展和實現都涉及到它時,它將如何工作?

class A {
  void test() {
    System.out.println("One");
  }
}

interface J {
  void first();
}

// This class object can referenced using A like A a = new B()
class B extends A {
  // code    
}

// This class object can referenced using J like J j = new B()
class B implements J {
  // code
}

// my question is what happens in case of below which referencing for runtime polymorphism?
class B extends A implements J {
  // code 
}

不能編譯為:

Main.java:16: error: duplicate class: B
class B implements J {
^
Main.java:21: error: duplicate class: B
class B extends A implements J {
^
2 errors

當一個類的擴展和實現都涉及到它時,它將如何工作?

假設這是你的問題。

extend關鍵字用於擴展超類。

工具用於實現接口


接口和超類之間的區別在於,在接口中,您不能指定整體的特定實現(僅接口的“接口” 不能被實例化,而是被實現 )。因此,這意味着您只能指定所需的方法合並,但不能以相同的方式在您的項目中實現它們。

引用超類方法與接口方法時可能會有一些差異,特別是當您使用super調用它們時。 考慮以下接口/類:

public interface MyIFace {
    void ifaceMethod1();
}


public class MyParentClass {
    void parentClassMethod1();
}

public class MyClass extends MyParentClass implements MyIFace {

    public void someChildMethod() {
        ifaceMethods(); // call the interface method
        parentClassMethod1(); // call the parent method just like you would another method. If you override it in here, this will call the overridden method
        super.parentClassMethod1(); // you can use for a parent class method. this will call the parent's version even if you override it in here
    }

    @Override
    public void ifaceMethod1() {
      // implementation
    }

}

public class AnExternalClass {
    MyParentClass c = new MyClass();
    c.parentClassMethod1(); // if MyClass overrides parentClassMethod1, this will call the MyClass version of the method since it uses the runtime type, not the static compile time type
}

通常,調用不帶super的方法將調用由類的運行時版本實現的方法(無論該方法是來自類還是來自接口)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM