黑马程序员--this和super关键字

来源:互联网 发布:大数据主要应用领域 编辑:程序博客网 时间:2024/05/27 12:22

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——
this和super关键字常用来指代父类对象与子类对象的关键字。
*this 关键字
-this是Java的一个关键字,表示当前对象。
-this可以出现在实例方法和构造方法中,但不可以出现在static方法中。
-this关键字出现在类的构造方法中时,代表使用该构造方法所创建的对象。
-this关键字出现在类的实例方法中时,代表正在调用该方法的当前对象。

例如:
public class MyDate {
private int day, month, year;
public void tomorrow() {
this.day = this.day + 1; //this.day指的是当前对象的day字段
}
}

class Demothis{
int a; //成员变量
public Demo(int a) //在成员方法定义时,我们使用的形式参数与成员变量名称相同,这时我们要用到this
{
this.a = a;
}
}

*super关键字
在子类中通过super来实现对父类成员的访问。我们知道,this用来引用当前对象,与this类似,super用来引用当前对象的父类。
(1) 访问父类被隐藏的成员变量,如:
super.variable;
(2)调用父类中被覆盖的方法,如:
super.Method([paramlist]);
(3)调用父类的构造函数,如:
super([paramlist]);
通过super关键字访问父类中被隐藏的成员变量
class Father
{
int x=0;
}

class Child extends Father{
int x=1;
Child() {
System.out.println (super.x);}
public static void main(String args[]){
new Child(); //super.x=0
}
}

子类的构造方法中,通过super关键字调用父类的构造方法
public class Student extends Person {
public Student(String myName, int myAge) {
super(myName, myAge);
}
}

方法覆盖后,通过super关键字调用父类的方法
public class Student extends Person {
public void showInfo(){
super.showInfo();
System.out.println(“,你的英语成绩是:”+engScore+”, JAVA成绩是:”+javaScore”);
}
}

0 0