java中的方法重写和对象转换 [英] Method overriding and object casting in java

查看:128
本文介绍了java中的方法重写和对象转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>class Alpha
{
    public String doStuff(String msg)
    {return msg;}
}
class Beta extends Alpha
{
    public String doStuff(String msg)
    { return msg.replace('a','e');}
}
public class Main extends Beta
{ public String doStuff(String msg)
{
    return msg.substring(2);
}
  public static void main (String[]args)
  {
    List <Alpha> strs=new ArrayList<>();
    strs.add(new Alpha());
    strs.add(new Beta());
    strs.add(new Main());
    for(Alpha t:strs)
    {    
        System.out.println(t.doStuff("Java"));
    }
}
}



输出

Java
Jeve

va



我的尝试:



我的理解是:



在for循环中,

第一次迭代,

Alpha的匿名对象和Alpha的对象't'将指向同一位置,因此我们得到输出为Java



但是在第二个迭代,

Beta的匿名对象的属性将被分配给't',我预期会抛出错误,但程序会产生输出。



有人能解释第二次和第三次迭代中发生了什么吗?


output
Java
Jeve
va

What I have tried:

my understanding is that :

In the for loop,
first iteration,
the anonymous object of Alpha and object 't' of Alpha will be pointing to the same location so we get the output as Java

but in the second iteration,
the properties of the anonymous object of Beta will be assigned to 't' which I expected will throw an error but the program produces the output.

Could anyone explain what's happening in the second and third iterations ?

推荐答案

这是多态性(Java™教程>学习Java语言>接口和继承) [ ^ ]功能。



以上链接描述了它,提供了一个与你类似的例子,最后指出:

It is a Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)[^] feature.

The above link describes it, provides an example similar to yours, and finally nails it down:
Quote:

Java虚拟机(JVM)为每个变量中引用的对象调用适当的方法。它不会调用由变量类型定义的方法。此行为称为虚方法调用,并演示Java语言中重要多态性功能的一个方面。

The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.



在您的示例中,列表中的对象的类型为 Alpha Beta Main 。即使 t 被声明为 Alpha ,相应的 doStuff()调用真实对象的方法。


In your example the objects in the list are of type Alpha, Beta, and Main. Even while t is declared as Alpha, the appropriate doStuff() method of the "real" object is called.


这篇关于java中的方法重写和对象转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆