在子类中使用super调用父类的方法
定义一个父类Person
package com.kuangstudy.Demo06;
public class Person {
protected String name = "kuangshen";
}
使用子类Student继承父类
package com.kuangstudy.Demo06;
public class Student extends Person{
private String name = "李浩";
public void test(String name){
System.out.println(name); //张三---是参数name
System.out.println(this.name);//李浩
System.out.println(super.name);//kuangshen
}
}
使用Application类进行测试
package com.kuangstudy.Demo06;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("张三");
}
}
运行结果
![]()
Super的注意点
- super调用父类的构造方法,必须在构造方法的第一个
- super只能出现在子类的方法或者构造方法中!
- super和this不能同时调用构造方法
super Vs this
- 代表的对象不同
this :本身调用者这个对象
super:代表父类对象的应用
- 前提
this:没有继承也可以使用
super:只能在继承条件才可以使用
- 构造方法
this() :本类的构造
super():父类的构造!