Java中的变量和方法阴影 [英] Variable and Method shadowing in Java

查看:130
本文介绍了Java中的变量和方法阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想知道为什么静态方法不能被实例方法遮蔽,(我知道为什么,它会在某些情况下导致模糊),而静态变量可以被实例变量遮蔽(它适用仅适用于子类)。

Basically I would like to know why a static method cannot be shadowed by an instance method, (I know why, it will lead to ambiguity in certain circumstances), whereas a static variable can be shadowed by an instance variable (it applies only for subclasses).

示例:

public class Apartment{

    static int area = 10;

    public static int getArea(){
        return area;
    }
}

class BedroomFlat extends Apartment {

    int area = 10;// no problem at all 

    public int getArea(){ // illegal line it cannot hide the super static method
        return area;
    }
}

所以如果我试图宣布 int area (实例变量)以及超类中的 static int area 它会给出错误但是在声明时它不会发生即使从子类仍然可以看到 static int area 的子类。

So if I tried to declare int area (instance variable) along with the static int area in the super class it would give an error but it does not happen when declared in the subclass even though the static int area is still visible from the subclass.

对于尝试使用实例方法隐藏静态方法和尝试使用实例变量隐藏静态变量之间的行为。

What's exactly the difference in terms of behavior between trying to shadowing a static method with an instance method and trying to shadowing a static variable with an instance variable.

提前致谢。

推荐答案

在您的子类(BedroomFlat) ),编译器不允许您声明一个与基类中静态方法名称相同的实例方法,因为方法重写仅适用于实例方法。扩展类只使实例方法可用于子类以进行重写(而不是类方法,即静态)。
此外,当您尝试声明一个具有与静态方法相同签名的方法时,编译器将抛出一个错误,指出您不能覆盖静态方法,因为重写发生在实例方法中。

In your sub class (BedroomFlat), compiler will not allow you to declare a instance method with the same name as that of static method in the base class because method overriding is only applicable to instance methods. Extending a class only make instance methods available to the sub class for overriding(and not class methods i.e. static). Moreover, when you try to declare a method with same signature as that of a static method, compiler will throw an error saying you cannot override a static method, as overriding takes place for instance method.

但是编译器不会阻止你声明一个与超类中的静态变量同名的实例变量,因为变量不是覆盖的候选者。

But compiler will not stop you from declaring a instance variable with the same name as static one from super class, because variables are not the candidates for overriding.

这篇关于Java中的变量和方法阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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