What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
Nit*_*dra 71
让我们考虑一下这种情况
class Animal {
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void anotherEat() {
super.eat();
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eat();
d.anotherEat();
}
}
Run Code Online (Sandbox Code Playgroud)
输出将是
animal : eat
dog : eat
animal : eat
Run Code Online (Sandbox Code Playgroud)
第三行是打印"动物:吃",因为我们正在打电话super.eat()
.如果我们打电话this.eat()
,它会打印成"狗:吃".
Jay*_*ker 52
super
用于访问基类的方法,同时this
用于访问当前类的方法.
扩展这个概念,如果你写super()
,它指的是基类的构造函数,如果你写this()
,它引用你正在编写这段代码的类的构造函数.
Eri*_*son 19
this
是对作为当前类输入的对象的引用,并且super
是对作为其父类键入的对象的引用.
在构造函数中,this()
调用当前类中定义的构造函数. super()
调用父类中定义的构造函数.构造函数可以在任何父类中定义,但它将引用最接近当前类的重写.以这种方式调用其他构造函数可能只能作为构造函数中的第一行.
调用方法的工作方式相同.调用this.method()
调用当前类中定义的方法,该方法super.method()
将调用父类中定义的相同方法.
Ste*_*n C 10
从你的问题来看,我认为你真的在询问构造函数链的使用this
和super
构造函数; 例如
public class A extends B {
public A(...) {
this(...);
...
}
}
Run Code Online (Sandbox Code Playgroud)
与
public class A extends B {
public A(...) {
super(...);
...
}
}
Run Code Online (Sandbox Code Playgroud)
区别很简单:
的this
形式链在当前类中的构造; 即在A
课堂上.
该super
表格链的直接超类构造函数; 即在B
课堂上.
this
指当前类的引用.
super
指当前类的父级(称为super
关键字).
通过这样做this
,它允许您访问当前类的方法/属性(包括其自己的私有方法/属性).
super
允许您访问父(基)类的公共/受保护方法/属性.您无法看到父级的私有方法/属性.
注意:
我们只能在构造函数中使用super()和this()而不是其他任何地方,任何尝试这样做都会导致编译时错误.
我们必须保持super()或this()作为构造函数的第一行,但不能同时保持两者.
注意:除静态区域(静态块或方法)外,我们可以在类中的任何位置使用它们,任何尝试这样做都会导致编译时错误.