this对象调用父类的方法

一.当子类没有定义方法时,this对象会寻找父类中的方法

二.

package com.cracker;


class Parent{
    
    public void action() {
        
    }
    
    public void sleep() {
        System.out.println("父类:嗷呜");
    }
}

class Child extends Parent{
    
    @Override
    public void action() {
        this.sleep();
    }
    
}

public class Demo1 {
    
    public static void main(String[] args) {
        Parent child = new Child();
        child.action();
    }
}

结果:

父类:嗷呜

如果子类中重写了sleep()方法,this.sleep()则调用重写的sleep()方法

猜你喜欢

转载自www.cnblogs.com/cracker13/p/12340909.html