看J2SE的时候遇到了super这个关键字,这个关键字是在之前学习C#视频中没有接触到的。然后就深入的看了看这个关键字到底是干什么的。
super关键字
在java中super关键字是一个引用变量,用于直接引用父类对象。可以使用关键字来访问父类的数据成员或字段。如果父类和子类具有相同的字段,则使用来指定为父类数据成员或字段。
class Animal { String color = "white"; } class Dog extends Animal { String color = "black"; void printColor() { System.out.println(color);// prints color of Dog class System.out.println(super.color);// prints color of Animal class } }
this关键字
在java中this关键字可用于任何实例方法内指向当前对象,也可指向对其调用当前方法的对象,或者在需要当前类型对象引用时使用。
this.属性名:一般情况下,普通方法访问其他方法、成员变量时无须使用 this 前缀,但如果方法里有个局部变量和成员变量同名,但程序又需要在该方法里访问这个被覆盖的成员变量,则必须使用 this 前缀。
public class Teacher { private String name; // 名称 } // 创建构造方法,为上面的属性赋初始值 public Teacher(String name) { this.name = name; // 设置名称 }
this.方法名:让类中一个方法,访问该类里的另一个方法或实例变量。
// 定义一个run()方法,run()方法需要借助jump()方法 public void run() { // 使用this引用调用run()方法的对象 this.jump(); System.out.println("正在执行run方法"); }
this.构造函数
public Student(String name) { this.name = name; }
this关键字是说本类中的一些事情,super是说父类中的一些事情。如果我们要引用本类的成员变量就使用this关键字,如果我们要引用父类的成员变量就使用super关键字。