2023/10/13 动手动脑

class Parent {
    void display() {
        System.out.println("这是父类的display方法");
    }
}

class Child extends Parent {
    @Override
    void display() {
        super.display(); // 调用父类的display方法
        System.out.println("这是子类的display方法");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}

在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

输出结果为:

这是父类的display方法
这是子类的display方法

public class people {
    public String dish;
    public String job;
    public people(String job,String dish)
    {
        this.job=job;
        this.dish=dish;
    }
    public String toString()//注意public类型
    {
        return job+"点了"+dish;
    }
}
package 实践与练习;

public class doctor extends people{
    doctor (String job,String dish){
        super(job,dish);
    }
}
package 实践与练习;

public class student extends people{
    student(String job,String dish){
        super(job,dish);
    }
}
package 实践与练习;

public class teacher extends people{
    teacher(String job,String dish){
        super(job,dish);
    }
}
package 实践与练习;

public class text {
    public static void main(String[] args)
    {
        people a=new teacher("老师","香辣肉丝");
        teacher b=(teacher) a;
        people c=new student("学生","火腿炒面");
        student d=(student) c;
        people e=new doctor("医生","麻辣香锅");
        doctor f=(doctor) e;
        System.out.println(b);
        System.out.println(d);
        System.out.println(e);
    }
}

在子类的display方法中,使用super.display()调用了父类的display方法,然后在子类的display方法中添加了额外的逻辑。这样,父类的方法被调用后,子类可以根据需要添加自己的处理逻辑。

 

posted @ 2023-10-13 21:40  伐木工熊大  阅读(29)  评论(0编辑  收藏  举报