前言
在一个实例方法或者是构造方法中,this引用指向当前的对象—方法调用或者是构造方法调用的对象。你可以在实例化方法或者构造方法中,使用this引用任何成员。super引用指向父类对象,你可以在实例化方法或者构造方法中,使用super引用父类的protected、public成员变量和成员函数。
在字段中使用this
使用this关键字的最常见的原因,是字段被方法或构造函数的参数隐藏了。
例如,Point类是这样写的:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
等价于
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
构造方法的每个参数都隐藏了对象的字段—在构造方法里,x是构造方法的第一个参数的局部副本,引用Point字段x,构造方法必须使用this.x.
在构造方法使用this
在构造方法里,你可以使用this关键字调用类的另一个构造方法。这种是显式构造方法调用。这里有一个Rectangle类:
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
super关键字试用
public class C{//父类
protected String name="parent value";
}
public class E extends C{
String name = "child name";
/**
* 打印父类name
*/
void printParentName(){
System.out.println(super.name);
}
/**
* 打印自身name
*/
void printMyName(){
System.out.println(this.name);
}
public static void main(String[] args) {
E child = new E();
child.printParentName();
child.printMyName();
}
}
输出:
parent value
child name
private, protected,package,public 的作用域参考权限修饰符
如若转载,请注明出处:https://www.javaidea.cn/article/7394.html