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(),请问还有什么其他的方法么?
解决方案 »
- Eclipse/EasyEclipse都说不支持JFrame
- Fizzbuzz问题求助
- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
- 如何写一个给 c 调用的java程序
- 各位高人,怎样设置一个JButton的事件,使得用默认浏览器(ie或者firefox),打开一个已经储存的网页呢?
- 给我妹妹求一个JAVA老师
- 劳驾问一个小问题,谢谢了
- 请问,下面这段代码能返回一个有记录的结果集吗?
- 怎样使jbuilder7能使用import javax.servlet.http.*;语句?
- 怎样实现菜单和工具栏的事件传递的统一??
- 一道押宝题的思考!
- 用java 取whois 的问题
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;
}
public void addHead(){
super.addHead();
}}
第一,你说override?你在Parent里面
private void addHead()
定义为私有的,子类根本不继承,又何来覆盖呢?概念上的,当然也许LZ的说法疏忽了吧。
第二,你的描述我没有看明白。
你是说,输出的内容仍是这样,其他的做法吗?
改成
protected void addHead(){
public class Parent{
protected void addHead(){
txt = "Here is father txt " + txt;
System.out.println("@ addhead: " + txt);
}}
public class Child extends Parent{
//重写addHead方法
public void addHead(){
super.addHead();
txt = "Here is Child txt " + txt;
System.out.println("@ addhead: " + txt);
}}
public class Parent{
protected void addHead(){
txt = "Here is father txt " + txt;
System.out.println("@ addhead: " + txt);
}}
public class Child extends Parent{
//重写addHead方法
public void addHead(){
super.addHead();
txt = "Here is Child txt " + txt;
System.out.println("@ addhead: " + txt);
}}
就是 6楼的这种写法。
public class Child extends Parent{ public Child() {
super.setText("child");
}
}