首页 > 解决方案 > 超级关键字歧义

问题描述

以下程序

class Feline {
    public String type = "f ";

    public Feline() {
        System.out.print("feline ");
    }
}

public class Cougar extends Feline {

    public Cougar() {
        System.out.print("cougar ");
    }

    void go() {
        type = "d ";
        System.out.print(this.type + super.type);
    }

    public static void main(String[] args) {
        new Cougar().go();
    }
}

产生以下输出。

feline cougar d d 

我无法理解为什么super.type在生成输出时没有从超类中获取 的值并打印 anf而不是打印本地值d。有人可以在这里提供一些帮助吗?

标签: javasuper

解决方案


它是相反的,现在你type被合并在一起,当你改变 的值时type,它会覆盖super.type

这里有一个简短的例子作为解释:

void go() {
    System.out.print(this.type);
    type = "d ";
    System.out.print(this.type + super.type);
}

输出:

f d d 

它实际上是将super.type值更改fd


推荐阅读