Java 获取超类字段的值
在下面的代码中,Java 获取超类字段的值,java,inheritance,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 cl
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
的值
蒂亚 如果我将类
美洲狮更改为
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);
}
}
而不是代码生成的输出(这是)
这不是OO做事的方式,因为Cougar
Feline
。您看到的行为(超类中的值变化)就是因为这种关系。最后,为了保持值的不同,您需要像上面那样对猫
类型进行阴影处理
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”
解决方案:
this.type = "c "; //this.type will return the super.type
您需要在Cougar
类中创建一个type
变量来更改的范围。type
您覆盖了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(); }
}
我不明白你这么做的真正意义。
如果确实要区分类型,则应使用Cougar声明类型:
public class Cougar extends Feline {
public String type = "c ";
...
}
公共字符串type=“f”
存在于您的超类中。因此,它被继承到您的子类。当您调用this.type=“c”
时,它所做的是更改存在于超类中的类型变量的值。因此,您得到的输出是正确的。您只需创建一个Cougar实例,在开始时,type字段是“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(); }
}
由于您正在扩展猫类
类,因此通过分配c
来覆盖type
值。如果您在子类中创建它,那么您将使用super.type
获得所需的字符串值。不要这么快接受。从面向对象的角度来看,您试图实现的目标一点也不清楚,您接受的答案是“错误的”。跟踪超类成员是正确的做法是非常罕见的,这将打破其他人对类层次结构行为的期望。你需要澄清你正在得到的行为和你的期望,以及为什么你认为某些事情是错误的。
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(); }
}