在Java中,如果子类使用实例子变量隐藏静态父变量,哪个变量将继承方法使用? [英] In Java, if a child class shadows a static parent variable with an instance child variable, which variable will inherited methods use?

查看:93
本文介绍了在Java中,如果子类使用实例子变量隐藏静态父变量,哪个变量将继承方法使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一件坏事,如 Java中的父类和子类可以具有相同的实例变量吗?。 (如果父变量名称被更改怎么办?那么它将不再被遮蔽。)但是,我仍然好奇不同的静态/非静态变量是否会相互影响。一方面我希望它们是相同的变量名称,因此会被遮蔽,但另一方面,似乎编译器可能基于静态区分这两者。

This is probably a bad thing to do, as discussed in Can parent and child class in Java have same instance variable?. (What if the parent variable name is changed? Then it will not be shadowed anymore.) However, I am still curious whether variables that are differently static/nonstatic will shadow each other. On one hand I would expect they are the same variable name so would be shadowed, but on the other hand it seems like the compiler might distinguish between the two based on staticness.

推荐答案

来自 Java语言规范


如果表达式名称由单个标识符组成,则
必须是一个可见的声明,表示
标识符出现时的范围内的本地
变量,参数或字段。否则,发生编译时错误。

If an expression name consists of a single Identifier, then there must be exactly one visible declaration denoting either a local variable, parameter or field in scope at the point at which the the Identifier occurs. Otherwise, a compile-time error occurs.

如果声明声明了一个final字段,则该字段的含义为
该字段的值。否则,表达式名称
的含义是声明声明的变量。

If the declaration declares a final field, the meaning of the name is the value of that field. Otherwise, the meaning of the expression name is the variable declared by the declaration.

如果超类中的方法引用对于该类的特定字段(静态或其他),只有该类的字段声明将在该点的范围内;子类的任何字段(静态或其他)都不在范围内。因此,该方法将始终使用超类字段,即使子类继承它并且阴影该字段。

If a method in a superclass refers to a particular field (static or otherwise) of that class, only that class's declaration of the field will be in scope at that point; any fields (static or otherwise) of subclasses will not be in scope. Therefore, the method will always use the superclass field, even if a subclass inherits it and shadows that field.

这个答案完全根据我的新理解重写这个问题。以下是我的第一个答案,为后人保留。

来自 Java语言规范


字段,局部变量,方法参数,
构造函数参数或名为 n 的异常处理程序参数的声明 d 影响
任何其他字段的声明,局部变量,方法
参数,构造函数参数或异常处理程序参数
名为 n ,它们在整个$中出现 d 的范围内b $ b范围 d

A declaration d of a field, local variable, method parameter, constructor parameter or exception handler parameter named n shadows the declarations of any other fields, local variables, method parameters, constructor parameters or exception handler parameters named n that are in scope at the point where d occurs throughout the scope of d.

这表明编译器需要隐藏父变量,无论静态。

This suggests that compilers are required to shadow parent variables, regardless of staticness.

请注意,这些都与继承的方法无关,无论子类是否隐藏它们,它们总是使用原始变量。我怀疑这不是你要问的问题。

Note that none of this is relevant to inherited methods, which always use the original variables regardless of whether a subclass shadows them. I suspect this isn't what you meant to ask.

这篇关于在Java中,如果子类使用实例子变量隐藏静态父变量,哪个变量将继承方法使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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