繁体   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