super 与 this 关键字

2023-07-29,

super与this用法相似:

1.普通的直接引用

2.形参与成员名字重名,用 this 来指代类本身,super指代父类

public class Students extends Person {
String name;
public void setName(String name) {
this.name = name;
}
public void setFName(String name) {
super.name = name;//父类名字
}
}

3.在构造器中使用

super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。

package day06_oop.test2;

class t {
public static void prt(String s) {
System.out.println(s);
} t() {
prt("父类无参");
}//构造方法(1) t(String name) {
prt("父类含参" + name);
}//构造方法(2)
} class Chinese extends t {
Chinese() {
super(); // 调用父类构造方法(1)
prt("子类无参");
} Chinese(String name) {
super(name);// 调用父类具有相同形参的构造方法(2)
prt("子类含参" + name);
} Chinese(String name, int age) {
this(name);// 调用具有相同形参的构造方法(3)
prt("子类:调用子类具有相同形参的构造方法:his age is " + age);
} public static void main(String[] args) {
Chinese cn = new Chinese("参数二", 18);
}
}

结果:

父类含参参数二
子类含参参数二
子类:调用子类具有相同形参的构造方法:his age is 18

super 与 this 关键字的相关教程结束。

《super 与 this 关键字.doc》

下载本文的Word格式文档,以方便收藏与打印。