子类调用父类被重写的方法

一、代码

package com.atguigu.exer1;


//==========        Son         ===================
public class Son extends Father {
    
    public String str = "子类变量";

    public void printf(String str){
        
        System.out.println(str+"这是子类的方法");
    }
    
    public void test(){
        printf("什么都不使用=======>");
        this.printf("使用this=======>");
        super.printf("使用super=======>");
        printfOnly("子类没重写,就会调用父类的方法");
        
        System.out.println("str is ===========>"+str);
        System.out.println("super.str is ===========>"+super.str);
        System.out.println("子类没有同名变量,就会去找父类的变量 ===========>"+strOnly);

    }
    
    public static void main(String[] args) {
        Son son = new Son();
        son.test();
        
    }
    
    
}

//==========        Father         ===================
class Father{
    public String str = "父类变量";
    
    public String strOnly = "父类变量,子类没有同名变量";
    
    public void printf(String str){
        System.out.println(str+"这是父类的方法");
    }
    
    public void printfOnly(String str){
        System.out.println("这是父类的方法,子类没有重写的方法====>"+str);
    }

}

二、super不能在main中使用,因为main方法为静态方法

原文地址:https://www.cnblogs.com/developmental-t-xxg/p/9962329.html