10.13(子类和父类覆盖)

发布时间 2023-10-14 09:50:16作者: 徐星凯
package homework;
public class text
{

    public String toString()
    {
        return "Fruit toString.";
    }

    public static void main(String args[])
    {
        text f=new text();
        System.out.println("f="+f);
        //    System.out.println("f="+f.toString());
    }
}

此处的toString函数覆盖了Object中的toString函数

 在子类中调用被覆盖的函数用super作为父类对象再调用函数即可

package homework;
public class text
{
    public static void main(String[] args){

        child baby=new child();
        baby.eat();
    }

}
class father{
    public father(){
        System.out.println("father created");
    }
    public void eat(){
        System.out.println("两碗大米饭");
    }
}
class child extends father{
    public child(){
        super();
        System.out.println("child created");
    }
    public void eat(){
        System.out.println("一小碗米饭");
        super.eat();
    }
}