Java关键字介绍之this与super

总结关键字this与super用法。
author: ZJ 07-3-12
Blog: [url]www.wendangwang.com[/url]
1.什么是super?什么是this?
super关键字表示超(父)类的意思。this变量代表对象本身。
2.使用super&this调用成员变量和方法
可以使用super访问父类被子类隐藏的变量或覆盖的方法。当前类如果是从超类继承而来的,当调用super.XX()就是调用基类版本的XX()方法。见示例1。
当类中有两个同名变量,一个属于类(类的成员变量),而另一个属于某个特定的方法(方法中的局部变量),使用this区分成员变量和局部变量。见示例2。

示例1
class Person {
protected void print() {
System.out.println("The print() in class Person.");
}
}

public class DemoSuper extends Person {
public void print() {
System.out.println("The print() in class DemoSuper.");
super.print();// 调用父类的方法
}

public static void main(String[] args) {
DemoSuper ds = new DemoSuper();
ds.print();
}
}

结果:
The print() in class DemoSuper.
The print() in class Person.

示例2
public class DemoThis {
private String name;

public void setName(String name) {
this.name = name;// 前一个name是private name;后一个name是setName中的参数。
}
}
3.使用this表示当前调用方法的对象引用
假设你希望在方法的内部获得对当前对象的引用,可使用关键字this。this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。见示例3。

示例3
Button bn;

bn.addActionListener(this);
4.使用super&this调用构造子
super(参数):调用基类中的某一个构造函数(应该为构造函数中的第一条语句)。见示例4。
this(参数):调用本类中另一种形成的构造函数(应该为构造函数中的第一条语句)。 见示例5。

示例4
class Person {
public static void prt(String s) {
System.out.println(s);
}

Person() {
prt("A Person.");
}

Person(String name) {
prt("A person name is:" + name);
}
}

public class Chinese extends Person {
Chinese() {
super();// 调用父类构造函数。
prt("A chinese.");
}

Chinese(String name) {
super(name);// 调用父类具有相同形参的构造函数。
prt("his name is:" + name);
}

public static void main(String[] args) {
Chinese cn = new Chinese();
cn = new Chinese("kevin");
}
}

结果:
A Person.
A chinese.
A person name is:kevin
his name is:kevin

示例5
Point(int a,int b){
x=a;
y=b;
}
Point(){
this(1,1); //调用point(1,1),必须是第一条语句。
}
5.使用super&this应该注意些什么?
1)调用super()必须写在子类构造方法的第一行,否则

你可能喜欢

  • JAVA关键字
  • 关键字排名
  • JAVA简历
  • 百度关键字
  • JAVA常用类
  • 网站关键字优化

Java关键字介绍之this与super相关文档

最新文档

返回顶部