获取超类字段的值

时间:2014-08-25 02:57:08

标签: java inheritance

在以下代码中,super.type带来this.type的值。

// http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=303&p_certName=SQ1Z0_803

class Feline {
    public String type = "f ";
    public void hh(){ System.out.print("FFFFF ");}
}


public class Cougar extends Feline {
    public void hh(){ 
        super.hh();
        this.type = "c ";
        System.out.print("CCCCC "+this.type + super.type);
    }

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

}

如何在后代类中获得super.type的值?

TIA。

6 个答案:

答案 0 :(得分:2)

你的超级课程中存在

public String type = "f "。所以它被继承到你的子类。当你调用this.type = "c"它所做的是改变了超类中存在的类型变量的值。所以你得到的输出是正确的。

答案 1 :(得分:2)

你只需要创建一个Cougar实例,在开始时,类型字段是“f”,但是,在打印super.type之前,你已经为它重新赋值“c”。

您可以使用以下代码来解决这个问题:

class Feline {
    public String type = "f ";
    public void hh(){ System.out.print(type);}
}


public class Cougar extends Feline {
    public void hh(){ 
        super.hh();
        this.type = "c ";
        System.out.print(this.type + super.type);
    }

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

}

答案 2 :(得分:1)

How can i get the value of super.type in the descendant class ?

<强>问题:

this.type = "c "; //this.type will return the super.type

您已将super.type的值引用至"c ",从而打印"c"

<强>溶液

您需要在type课程中创建Cougar变量,以更改this.type的范围。

答案 3 :(得分:0)

你覆盖Cougar类中的type值。这样做:

this.type = "c ";

如果你想在super.type和this.type之间有区别,那么将名字类型的字段添加到Cougar中。

public class Cougar extends Feline {
    public String type = ""; //add this
    public void hh(){ 
        super.hh();
        this.type = "c ";
        System.out.print("CCCCC "+this.type + super.type);
    }

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

}

答案 4 :(得分:-1)

我无法理解你这样做的真正含义。 如果你真的想要区分类型,你应该在Cougar中声明类型:

public class Cougar extends Feline {
    public String type = "c ";

    ...
}

答案 5 :(得分:-2)

如果我将课程Cougar更改为

public class Cougar extends Feline {
    public String type = "c "; // <-- shadow Feline's type.
    public void hh() {
        super.hh();
        // this.type = "c ";
        System.out.print("CCCCC " + this.type + super.type);
    }
}

然后我得到你似乎期望的输出

FFFFF CCCCC c f 

而不是代码产生的输出(是)

FFFFF CCCCC c c 

这不是OO的做事方式,因为Cougar is-a Feline。您看到的(超类中值的变化)是因为这种关系。最后,为了保持值不同,您需要隐藏Feline类型,如上所述。

相关问题