this用法
this的用法在java中大体可以分为3种:
//
1.普通的直接引用
class test ... {
private int x,y;
public test(int x,int y) ...{
setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
}
}
// 2.方法中的某个形参名与当前对象的某个成员有相同的名字.为了不混淆,使用this区分有this引用的是成员,没有this是形参
class test ... {
private int x,y;
public test(int x,int y) ...{
setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
}
setX(int x)...{
this.x = x;//this.x是引用的对象,x是setX(int x)中的行参x
}
}
// 3.引用构造函数
class test ... {
public int x,y;
public test(int x,int y)...{
this.x = x;
this.y = y;
}
public test()...{
this.(2,0)//构造函数调用其他构造函数的方法,这个例子调用上面那个复用构造函数的方法
}
}
class test ... {
private int x,y;
public test(int x,int y) ...{
setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
}
}
// 2.方法中的某个形参名与当前对象的某个成员有相同的名字.为了不混淆,使用this区分有this引用的是成员,没有this是形参
class test ... {
private int x,y;
public test(int x,int y) ...{
setX(x);//也可以写为this.setX(x);这种情况下this可以省略.
}
setX(int x)...{
this.x = x;//this.x是引用的对象,x是setX(int x)中的行参x
}
}
// 3.引用构造函数
class test ... {
public int x,y;
public test(int x,int y)...{
this.x = x;
this.y = y;
}
public test()...{
this.(2,0)//构造函数调用其他构造函数的方法,这个例子调用上面那个复用构造函数的方法
}
}
super用法
我一度认为只能作用在构造函数中,这种想法是错误的.
//
1.super运用在构造函数中
class test1 extend test ... {
public test1()...{
super();//调用父类的构造函数
}
public test1(int x)...{
super(x);//调用父类的构造函数,因为带形参所以super 也要带行参
}
}
// 2.调用父类中的成员
class test1 extend test ... {
public test1()...{}
public f()...{//假如父类里有一个成员叫g();
super.g();//super引用当前对象的直接父类中的成员
}
}
class test1 extend test ... {
public test1()...{
super();//调用父类的构造函数
}
public test1(int x)...{
super(x);//调用父类的构造函数,因为带形参所以super 也要带行参
}
}
// 2.调用父类中的成员
class test1 extend test ... {
public test1()...{}
public f()...{//假如父类里有一个成员叫g();
super.g();//super引用当前对象的直接父类中的成员
}
}
super 用在构造函数时要放在第一行,相当于调用super就刷新了构造函数
super.g() 调用的成员 它引用当前对象的直接父类中的成员(用来访问直接父类中被隐藏的父类中成员数据或函数,基类与派生类中有相同成员定义时)
有相同成员定义时
这句话含义深刻 !
以上是个人理解如有错误请指出!