如何覆盖变量 [英] How are variables overridden

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

问题描述

package com.mycompany.myproject.mypkg;

interface MyInterface {
    public static final int k = 9;
}

class MyClass implements MyInterface {
    // int k = 89;
}

public class SampleThree extends MyClass {
    static int k = 90;

    public static void main(String args[]) {
        MyClass object = new SampleThree();
        System.out.println(object.k);
    }
}

为什么上面的程序打印的是'9'而不是'90'?

Why does the above program print '9' instead of '90'?

在Java中如何覆盖静态变量和成员变量?

How are static and member variables overridden in Java?

推荐答案

因为字段不支持多态. MyClass.k9(并且objectMyClass引用). SampleThree.k会给您90.每个类都有自己的一组变量.

Because fields do not support polymorphism. MyClass.k is 9 (and object is of refered to by MyClass). SampleThree.k would give you 90. Each class has its own set of variables.

(顺便说一句,IDE会在此处警告您,您正在通过实例而不是其类来访问静态变量.)

(Btw, An IDE would give you a warning here that you are accessing a static variable by an instance, rather than by its class.)

这篇关于如何覆盖变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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