Java中this与super的区别

this与super关键字在java中构造函数中的应用: 
**java

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(); } }

执行这段代码的结果为:this

An Animal 
A Dogspa

定义子类的一个对象时,会先调用子类的构造函数,而后在调用父类的构造函数,若是父类函数足够多的话,会一直调用到最终的父类构造函数,函数调用时会使用栈空间,因此按照入栈的顺序,最早进入的是子类的构造函数,而后才是邻近的父类构造函数,最后再栈顶的是最终的父类构造函数,构造函数执行是则按照从栈顶到栈底的顺序依次执行,因此本例中的执行结果是先执行Animal的构造函数,而后再执行子类的构造函数。code

class Animal { private String name; public String getName(){ name = name; } public Animal(String name) { this.name = name; } } class Dog extends Animal { public Dog() { super(name); } } class Test{ public static void main(String [] args){ Dog dog = new Dog("jack"); System.out.println(dog.getName()); } }

运行结果:对象

jack继承

当父类构造函数有参数时,若是要获取父类的private的成员变量并给其赋值做为子类的结果,此时在定义子类的构造函数时就须要调用父类的构造函数,并传值,如上例所示。get

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()的区别主要有如下: 
不一样点: 
一、super()主要是对父类构造函数的调用,this()是对重载构造函数的调用 
二、super()主要是在继承了父类的子类的构造函数中使用,是在不一样类中的使用;this()主要是在同一类的不一样构造函数中的使用 
相同点: 
一、super()和this()都必须在构造函数的第一行进行调用,不然就是错误的string

相关文章
相关标签/搜索