super 关键字
super 关键字的用法
访问父类被隐藏的成员变量(private的变量不能访问)
super.variable
访问父类中被重写的方法
super.method([paramlist])
访问父类的构造器
super([paramlist])
注意:无论是 super 还是 this,都必须放在构造方法的第一行。
this关键字
在构造器中指该构造器所创建的新对象
在方法中指调用该方法的对象
this关键字的用法
在类本身的方法或构造器中引用该类的实例变量和方法。
访问实例的变量:this.variable ,
访问实例的方法:this.method([paramlist])
将当前对象作为参数传递给其它方法或构造器
用来调用其他的重载的构造器
调用其他的构造器:this([paramlist]);
区别:
this()与super()
①this()和super()都是使用只能使用于构造方法中,
②this()调用本类的构造,如果括号内有形参,则是调用本类的与之相对应参的构造方法;super()调用父类指定的构造方法,
③都只能写在构造方法的第一句;
④super()可以不写,在不写的时候会默认调用父类的无参构造,
⑤this()与super()不能共存,两者只能使用一个。
super()函数在子类构造函数中调用父类的构造函数时使用,而且必须要在构造函数的第一行,例如:
class Animal {
public Animal() {
System.out.println("An Animal");
}
}
class Dog extends Animal {
public Dog() {
super();
System.out.println("A Dog");
//super();错误的,因为super()方法必须在构造函数的第一行
//如果子类构造函数中没有写super()函数,编译器会自动帮我们添加一个无参数的super()
}
}
class Test{
public static void main(String [] args){
Dog dog = new Dog();
}
}
执行这段代码的结果为:
An Animal
A Dog
定义子类的一个对象时,会先调用子类的构造函数,然后在调用父类的构造函数,如果父类函数足够多的话,会一直调用到最终的父类构造函数,函数调用时会使用栈空间,所以按照入栈的顺序,最先进入的是子类的构造函数,然后才是邻近的父类构造函数,最后再栈顶的是最终的父类构造函数,构造函数执行是则按照从栈顶到栈底的顺序依次执行,所以本例中的执行结果是先执行Animal的构造函数,然后再执行子类的构造函数。
this()函数
this()函数主要应用于同一类中从某个构造函数调用另一个重载版的构造函数。this()只能用在构造函数中,并且也只能在第一行。所以在同一个构造函数中this()和super()不能同时出现。
例如下面的这个例子:
class Mini extends Car {
Color color;
//无参数函数以默认的颜色调用真正的构造函数
public Mini() {
this(color.Red);
}
//真正的构造函数
public Mini(Color c){
super("mini");
color = c;
}
//不能同时调用super()和this(),因为他们只能选择一个
public Mini(int size) {
super(size);
this(color.Red);
}
所以综上所述,super()与this()的区别主要有以下:
不同点:
1、super()主要是对父类构造函数的调用,this()是对重载构造函数的调用
2、super()主要是在继承了父类的子类的构造函数中使用,是在不同类中的使用;this()主要是在同一类的不同构造函数中的使用
相同点:
1、super()和this()都必须在构造函数的第一行进行调用,否则就是错误的
例:这是this加点使用
public class DemoThis {
private String name;
private int age;
public DemoThis() {
this.print();// 你可以加上this来调用方法,
}
public DemoThis(String name, int age) {
this.name = name;
this.age = age;//这里就必须使用this加点的方法来区分,this.name就指代当前的属性name;
}
public void setName(String name) {
this.name = name; // 此处必须指明你要引用成员变量
}
public void setAge(int age) {
this.age = age;
}
public void print() {
System.out.println("Name=" + name + " Age=" + age); // 在此行中并不需要用this,
// 因为没有会导致混淆的东西
}
}
例:super加点的使用,
public class DemoThis {//父类
private String name;
private int age;
public DemoThis() {
}
public void print() {
System.out.println("哈哈哈哈。。。。。");
}
}
public class Demo extends DemoThis {//子类
public Demo(){
}
public void print(){
super.print();//只有这个时候用super.方法,其他我们基本用this.方法
System.out.println("嘿嘿嘿.......");
}
}
总结:有上面我们可知道,this.的使用范围要比super.的范围更大,除了上面要看重写前的效果能super,我们都是用this.的方法。
2:this()与super()
①this()和super()都是使用只能使用于构造方法中,
②this()调用本类的构造,如果括号内有形参,则是调用本类的与之相对应参的构造方法;super()调用父类指定的构造方法,
③都只能写在构造方法的第一句;
④super()可以不写,在不写的时候会默认调用父类的无参构造,
⑤this()与super()不能共存,两者只能使用一个。
参考博客:
http://www.cnblogs.com/qq1083735206/p/6160024.html
http://www.cnblogs.com/hasse/p/5023392.html
http://blog.youkuaiyun.com/u014285482/article/details/42347845