Java关键字介绍之this与super

来源:互联网 发布:招商银行软件怎么注销 编辑:程序博客网 时间:2024/04/27 15:03

出处:http://zhangjunhd.blog.51cto.com/113473/20531


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;// 前一个nameprivate name;后一个namesetName中的参数。
    }
}
3.使用this表示当前调用方法的对象引用
假设你希望在方法的内部获得对当前对象的引用,可使用关键字thisthis关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。见示例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()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。
 
2super()this()类似,区别是,super从子类中调用父类的构造方法,this()在同一类内调用其它方法。
 
3super()this()均需放在构造方法内第一行。
 
4)尽管可以用this调用一个构造器,但却不能调用两个。
 
5thissuper不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过。
 
6this()super()都指的是对象,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块。
 
7)从本质上讲,this是一个指向本对象的指针然而super是一个Java关键字。

0 0