17_super关键字 超,基,父

定义:子类对父类的引用,只能在非静态方法中使用。
    1.引用父类的成员变量时 格式为:super.成员变量名
    2.引用父类的非静态方法时,格式为:super.方法名(参数列表)
    3.引用父类的构造方法时, 格式为:super(参数列表);
  super(参数列表)只能在构造方法中使用,而且必须是构造方法的第一条语句。

eg:

父类

package xxxxxx;

// 员工类  父类
public class Employee{
     //成员变量
     String name = "小刘";
     private int age;
     
     //成员方法
     protected void work() {
         System.out.println("尽心尽力的工作。。");
     }
    
}

子类

package xxxxx;

public class SuperDemo extends Employee{
    
    String name = "小王";
    
    // 普通的成员方法
    public void method() {
        System.out.println(this.name);
        super.name = "张三";
    } 
    public void method02(String name) {       
        super.name = name;
        System.out.println(super.name);
    }   
    public SuperDemo() {  
        super();
        System.out.println("我要开始构造对象了。。。");
    }
    // Constructor call must be the first statement in a constructor
    public void method03() {
        //super();
    }
    public static void main(String[] args) {
        // 只能通过对象访问
        SuperDemo superDemo = new SuperDemo();
        //superDemo.method();        
        superDemo.method02("王五");
        //System.out.println(this.name);
    }
}
原文地址:https://www.cnblogs.com/rxqq/p/13922068.html