在将子类强制转换为超类之后调用方法的有趣行为 [英] interesting behavior of calling method after casting a subclass to a super class

查看:149
本文介绍了在将子类强制转换为超类之后调用方法的有趣行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A { 
    int i = 1; 
    int f() { return i; } 
} 
class B extends A { 
    int i = 2;
    int @Override f() { return -i; }
} 
public class override_test { 
    public static void main(String args[]) { 
         B b = new B(); 
         A a = (A) b;               // Cast b to an instance of class A. 
         System.out.println(a.i);   // Now refers to A.i; prints 1; 
         System.out.println(a.f()); // Still refers to B.f(); prints -2; 
    } 
}


$ b $ p我想知道为什么af()仍然引用Bf (),而ai指Ai

I am wondering why a.f() still refers to B.f() while a.i refers to A.i.

提前感谢!

推荐答案

一个方法,它将在实例类型(多态)在这种情况下实例是类型 B 即使引用类型 A

Simple rule is when you call a method, it will be on instance type (polymorphism) in this case instance is of type B even though reference is of type A.

当您调用变量时,它将在参考的类型。

When you call variable, it will be on Type of the reference.

about Ploymorphism

这篇关于在将子类强制转换为超类之后调用方法的有趣行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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