java 变量重写,Java中重写方法Vs类变量的方法

I was just trying some sample code for checking class variable overriding behavior in Java. Below is the code:

class A{

int i=0;

void sayHi(){

System.out.println("Hi From A");

}

}

class B extends A{

int i=2;

void sayHi(){

System.out.println("Hi From B");

}

}

public class HelloWorld {

public static void main(String[] args) {

A a= new B();

System.out.println("i->"+a.i); // this prints 0, which is from A

System.out.println("i->"+((B)a).i); // this prints 2, which is from B

a.sayHi(); // method from B gets called since object is of type B

}

}

I am not able to understand whats happening at these two lines below

System.out.println("i->"+a.i); // this prints 0, which is from A

System.out.println("i->"+((B)a).i); // this prints 2, which is from B

Why does a.i print 0 even if the object is of type B? And why does it print 2 after casting it to B?

解决方案

i is not a method - it's a data member. Data members don't override, they hide. So even though your instance is a B, it has two data members - i from A and i from B. When you reference it through an A reference you will get the former and when you use a B reference (e.g., by explicitly casting it), you'll get the latter.

Instance methods, on the other hand, behave differently. Regardless of the the type of the reference, since the instance is a B instance, you'll get the polymorphic behavior and get the string "Hi From B" printed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值