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(),请问还有什么其他的方法么?

解决方案 »

  1.   

    这样?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;
        }
        
        public void addHead(){
         super.addHead();
        }}
      

  2.   

    看到这了,说几句,若有什么不妥还请你包涵。
    第一,你说override?你在Parent里面
     private void addHead()
    定义为私有的,子类根本不继承,又何来覆盖呢?概念上的,当然也许LZ的说法疏忽了吧。
    第二,你的描述我没有看明白。
    你是说,输出的内容仍是这样,其他的做法吗?
      

  3.   

    private void addHead(){
    改成
    protected void addHead(){
      

  4.   


    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);
        }}
      

  5.   

    是啊是啊,private方法怎么override?
      

  6.   

    我的意思是不需要在子类中实现addHead函数即可通过Display函数直接调用父类中的addHead的功能,就像二楼所描述的那样非常感谢楼上的回复
      

  7.   

    那就在方法中调用super.addHead();
      

  8.   

    private改为protected,然后用多态,ok.
      

  9.   

    Java code
    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楼的这种写法。
      

  10.   

    你直接覆盖父类的Display函数就可以了
      

  11.   

    子类改成这样:
    public class Child extends Parent{    public Child() {
            super.setText("child");
        }
    }