问个面向对象的简单问题

guirenwang guirenwang 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

package Hello;

public class Hello {

public static void main(String arg[])
{
child c = new child();
c.setText("In main function");
c.Display();
}

}

package Hello;

public class Parent {
private String txt;
public Parent(){
txt = "parent";
}

public void setText(String t) {
System.out.println("Parent::setText");
txt = (t == null) ? "" : t;
}

public String getText(){
return txt;
}

private void addHead(){
txt = "Here is father txt " + txt;
System.out.println("@ addhead: " + txt);
}

public void Display(){
addHead();
System.out.println("txt = "+getText());
}
}

package Hello;

public class child extends Parent{
private String txt;
public child() {
txt = "child";
}

public void setText(String t){
System.out.println("child::setText");
txt = (t!=null)?t:"";
}

public String getText(){
return txt;
}

}

输出结果为:
child::setText
@ addhead: Here is father txt parent
txt = In main function

如果我想让父类的addHead()中的内容在子类调用Display()时也可以显示出来,出了在子类中overwrite函数addHead(),请问还有什么其他的方法么?
...全文

相关推荐

评论 14
收藏 已收藏
分享
返回顶部
guirenwang
Java SE 62,621 成员 307,251 内容