Variable shadowing

Variable shadowing

 

Today we’ll look into a rare feature of Java: variable shadowing

First, let’s define what is a shadowed field or method:

A field is considered shadowed when

  • a subclass of its declaring class declares a field with the same name and same
  • a variable having the same name and type is declared in the local scope
  • a method argument/parameter is declared with a same name and type

 

I Local variable shadowing

 

The above code will output

count = 5

because the count local variable declared at line 7 shadows the variable count declared at class level. If we want to access the instance variable, we need to add the thiskeyword.

 

II Method argument shadowing

This situation is very common even though we do not pay much attention to it. Below is a simple getter definition

The this keyword is mandatory to resolve the ambiguity. Without this, the compiler cannot know whether we are assigning the count method argument value to itself. If you remove the this keyword, you would get a compilation warning anyway.

 

III Superclass field shadowing

Let’s consider the following classes:

The execution gives:

val = SUPER_VAL

The val field has been declared in the SuperClass but is shadowed in the ChildClassbecause the latter declares another field with same name and type. Although theChildClass has been instantiated with “CHILD_VAL”, the execution of child.display()gives you “SUPER_VAL”.

The reason is simple. When the child instance is created, there are 2 variables val. The one from SuperClass with value “SUPER_VAL” and the one from ChildClass with injected value “CHILD_VAL” through constructor.

When the display() method is called, since it is define in the SuperClass, it is the val field in the context of SuperClass which is used. Not surprising that the output shows “SUPER_VAL”.

In the above modified code, we force the value for the hidden val field in SuperClasswith super.val = value, and the output gives:

val = CHILD_VAL

Now let’s add another class in the hierarchy

Obviously, the output will display

val = SUPER_VAL

The question now is: what if we want to display the val value of AncestorClass ? Obviously the super keyword only refers to the first parent class up in the class hierarchy.

Casting comes to the rescue. Indeed we can force the this keyword representing the current class instance to a particular type in the class hierarchy !

This time, we do have

val = ANCESTOR_VAL

转载于:https://www.cnblogs.com/hephec/p/4556602.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值