this和Super关键字

super()、super.和 this()、this.
1–this:在运行期间,哪个对象在调用this所在的方法,this就代表哪个对象,隐含绑定到当前“这个对象”。

2–super():调用父类无参构造器,一定在子类构造器第一行使用!如果没有则是默认存在super()的!
这是Java默认添加的super()。

3– super.是访问父类对象,父类对象的引用,与this.用法一致

4– this():调用本类的其他构造器,按照参数调用构造器,必须在构造器中使用,必须在第一行使用,
this() 与 super() 互斥,不能同时存在

5– this.是访问当前对象,本类对象的引用,在能区别实例变量和局部变量时,this.可省略,否则一定不能省!

6–如果子父类中出现非私有的同名成员变量时,子类要访问本类中的变量用this. ;子类要访问父类中的同名变量用super. 。

eg1:方法参数传递原理 与 this关键字
public class Demo {
public static void main(String[] args){
Point2 p1=new Point2();
p1.x=10;
p1.y=15;
p1.up(5);
System.out.println(p1.x+”,”+p1.y);//10,10
Point2 p2=new Point2();
p2.up(3);
System.out.println(p2.x+”,”+p2.y);//0,-3
}
}
class Point2{
int x;
int y;
public void up(int dy){
this.y=this.y-dy;
}
}

eg2:this. 和 this()
public class Demo {
public static void main(String[] args){
Cell c = new Cell();
System.out.println(c.x + “,”+c.y);//3,2
}
}
class Cell {
int x; int y;
public Cell() {
this(3,2);//调用本类的其他构造器
}
public Cell( int x, int y) {
this.x = x;
this.y = y;
}
}

eg3:super()
public class Demo {
public static void main(String[] args){
Xoo x=new Xoo(2);//Call Xoo(2)
Xoo x1=new Yoo();//Call Xoo(100)
}
}
class Xoo {
public Xoo(int s) {
System.out.println(“Call Xoo(“+s+”)”);
}
} // super()用于在子类构造器中调用父类的构造器

class Yoo extends Xoo {
// public Yoo() {}//编译错误,子类调用不到父类型无参数构造器
public Yoo() {
// super();//编译错误,子类调用不到父类型无参数构造器,因为若父类定义了带参的构造函数,系统就不会帮你生产无参数构造函数。
super(100);//调用了父类 Xoo(int) 构造器
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章