super 和 this 的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了super 和 this 的使用相关的知识,希望对你有一定的参考价值。

来源:http://zhangjunhd.blog.51cto.com/113473/20531/
1、什么是super?什么是this
super关键字表示超(父)类的意思。this变量代表对象本身。
2、使用super&this调用构造子
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
 
3、使用super&this应该注意些什么?
1)调用super()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。
 
2)super()和this()类似,区别是,super从子类中调用父类的构造方法,this()在同一类内调用其它方法。
 
3)super()和this()均需放在构造方法内第一行。
 
4)尽管可以用this调用一个构造器,但却不能调用两个。
 
5)this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过。
 
6)this()和super()都指的是对象,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块。
 
7)从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字。
his name is:kevin

以上是关于super 和 this 的使用的主要内容,如果未能解决你的问题,请参考以下文章

super和this的区别

java对于this和super的区别

this和super的用法

this和super的区别

super 与 this 同时使用问题

super and this