this关键字和super关键字
super关键字
- super只能出现在子类的方法和构造方法中;
- super调用构造方法时,只能是第一句;
- super不能访问法父类的private成员;
子类访问父类成员
- 访问父类构造方法
super(); 父类无参的构造方法
super(name); 父类有参的构造方法
- 访问父类属性
super.name;
- 访问父类方法
super.方法名();
public class Person {
//拥有属性和方法
protected String name = "父类名字";
public Person() {
System.out.println("我是父类的无参构造方法");
}
public void eat(){
System.out.println("Person eat Running....");
}
}
public class Student extends Person{
protected String name = "子类名字";
public Student() {
super();//默认调用父类的构造函数,并且只能放在第一行
System.out.println("子类的无参构造方法");
}
public void fun(String name){
System.out.println(name);//输出的是传入的参数
System.out.println(this.name);//输出的是本类中的name值
System.out.println(super.name);//输出的是父类中的name值
}
public void eat(){
System.out.println("Student eat Running....");
}
public void test(){
eat();
this.eat();
super.eat();
}
}
public class Test {
public static void main(String[] args) {
String name ="lqx";
Student student = new Student();
student.fun(name);
student.test();
}
/*
supler汪意点:
1. super调用父类的构造方法,必须在构造方法的第一个2. super必须只能出现在子类的方法或者构造方法中!3. super和 this不能 同时调用构造方法!
Vs this:
代表的对象不同:
this:本身调用者这个对象super:代表父类对象的应用前提
this:没有继承也可以使用
super:只能在继承条件才可以使用构造方法
this();本类的构造super():父类的构造!
*/
}

浙公网安备 33010602011771号