通过超级类/接口引用进行引用-Java
我是Java新手,我了解继承的基本概念。我有一个关于通过超类引用的问题。因为从超类继承或使用接口实现的类的方法可以通过超类引用(接口或类)来引用。当扩展和实现都涉及到一个类时,它将如何工作通过超级类/接口引用进行引用-Java,java,inheritance,Java,Inheritance,我是Java新手,我了解继承的基本概念。我有一个关于通过超类引用的问题。因为从超类继承或使用接口实现的类的方法可以通过超类引用(接口或类)来引用。当扩展和实现都涉及到一个类时,它将如何工作 class A { void test() { System.out.println("One"); } } interface J { void first(); } // This class object can referenced using A like A a = new
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
java:16:错误:重复类:B
B类实现了J{
^
java:21:错误:重复类:B
类B扩展了A和J{
^
2个错误
当扩展和实现都涉及到一个类时,它将如何工作
假设这是你的问题
extends关键字用于扩展超类
实现用于实现接口
接口和超类之间的区别在于,在接口中不能指定整个接口的特定实现(只有其“接口”-接口不能实例化,而只能实现)因此,这意味着你只能指定你想要的方法,但不能在同一个意义上在你的项目上实现它们。< P>当引用超级类方法和接口方法时,可能会有一些不同,特别是当你使用<代码>超级< /代码>来调用它们时。考虑这些接口/类:
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
调用方法将调用由类的运行时版本实现的方法(无论该方法是来自类还是来自接口)你能举例说明你的意思吗?不清楚你在问什么。举例说明?请检查链接..将调用Myclass版本。只有运行时类型用于多态调用。