java - 方法调用是如何发生的?

标签 java casting polymorphism method-invocation

我是 Java 编程新手,正在学习多态性。

__编辑__

根据我从大家那里收到的答案,我有代码:

在这里,我将 Derived 对象 (obj) 类型转换为 Base 类型,然后调用 method().

public class Tester {
    public static void main(String[] args) {
        Base obj=(Base)new Derived();
        obj.method();
    }   
}

class Base{
    public void method(){
        System.out.println("In Base");
    }
}

class Derived extends Base{
    public void method(){
        System.out.println("In Derived");
    }
}

我得到的输出是:“派生”。

因此,在类型转换之后,我的对象应该成为由 Base 类型引用的 Base 类型。 但这并没有发生?为什么?

类型转换对子->父转换有效吗?还是没有效果?

最佳答案

Base obj=new Derived();

上面的语句中,引用部分指向类型Base 。这就是编译器识别要考虑哪个类的方式。但你的代码会产生错误。在解释为什么会显示错误之前,让我解释一下上面语句的结构。

上述语句的结构:

  1. 声明-引用部分为Base obj .
  2. 实例化:new关键字是一个Java运算符,用于创建对象/在内存中分配空间。

  3. 初始化:new 运算符后跟对构造函数的调用,该构造函数初始化新对象。

DerivedBase 的子类,你可以调用 Derived 中的构造函数类(class)。这就是继承和多态性的工作原理。

好的,现在让我们回到错误部分。 obj.method()在您的代码中正在寻找一个函数 method()Base类但是method(int a)函数位于 Base类需要传递整数类型的参数。因此,为了使代码正常工作,调用语句必须类似于 obj.method(5)该语句之所以有效,是因为调用语句实际上将 5 传递给函数。

您的代码有一个简单的修复方法: Derived obj=new Derived();

你注意到了吗?

  • 我已将引用替换为类型 Derived .

为什么会这样?

  • 因为有method()在您的 Derived 中运行不需要整数参数的类。

关于 Java 中的继承,还有一个更令人惊奇的事实:

Everything possessed by a super-class is also possessed by the sub-class but the reverse is not true. And yes, the sub-class has the right to redefine any method/function it has inherited from super-class.

上述语句意味着以下代码将起作用:

Derived obj=new Derived();
obj.method(5);

您一定想知道 - 尽管 method() 这段代码如何工作?在Derived不需要争论。事实上,Derived没有method(int a) .

Well, the answer to this is the amazing fact I have mentioned above.

是的,method(int a)也属于Derived因为它是 Base 的子类.

但是下面提到的代码是如何工作的呢?

Derived obj=new Derived();
obj.method(5);

很简单,JVM 会查找 method(int a)上课Derived它找到了从Derived开始的函数继承了 Base 的功能类(class)。 还要记住这一点,子类也有权覆盖父类(super class)中的方法。这意味着您可以添加 method(int a)类中的函数Derived它覆盖从 Base 继承的原始方法.

继承是如何工作的?

  • 当您调用obj.method(5)时在上面的代码中,JVM首先在Derived中查找相同类型的任何被重写的方法。 。如果它没有找到任何被覆盖的方法,它就会在 inheritance hierarchy chain 中向上移动。到父类(super class)并寻找相同的方法。但事实恰恰相反。

关于java - 方法调用是如何发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392176/

相关文章:

c++ - C++中的简单序列化和反序列化

objective-c - 对象的条件初始化

java - 在 jscience 中使用惯性矩

java - 如何在Java Elasticsearch中设置超时

java - 如何将另一个包中的类连接到单独的包

c# - 从 IEnumerable 到 List 的强制转换无效

java - 应用ConKit3 : My changes in the Java Server files get overriden

c++ - 在 static_cast 之后执行类型安全检查的任何方法?

java - 从 BufferedReader(InputReader) 输入中解析 Integer.class

java - 如何在ArrayList中使用多态性?