关于实例方法和实例数据成员的进一步说明
一个类所有的实例(对象)调用的成员方法在内存中具有一份拷贝,尽管在内存中可能有多个对象,而数据成员在类的每个对象所在内存中都存在着一份拷贝。this变量允许相同的实例方法为不同的对象工作。每当调用一个实例方法时,this变量将被设置成引用该实例方法的特定的类对象。方法的代码接着会与this所代表的对象的特定数据建立关联。
例如:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
class
Point {
int x ,y;
public Point() {
}
public Point( int x, int y) {
this .x = x;
this .y = y;
}
public void output() {
System.out.println( " x = " + x);
System.out.println( " y = " + y);
}
public void output( int x , int y) {
this .x = x;
this .y = y;
}
public static void main(String[] args) {
Point pt;
pt = new Point( 5 , 5 );
pt.output( 6 , 6 );
pt.output(); // 当pt去调用output方法时,this.x的this就代表当前对象pt
Point pt2 = new Point();
pt2.output( 5 , 5 ); // 当pt2去调用output方法时,this.x的this就代表当前对象pt2
pt2.output();
}
}
int x ,y;
public Point() {
}
public Point( int x, int y) {
this .x = x;
this .y = y;
}
public void output() {
System.out.println( " x = " + x);
System.out.println( " y = " + y);
}
public void output( int x , int y) {
this .x = x;
this .y = y;
}
public static void main(String[] args) {
Point pt;
pt = new Point( 5 , 5 );
pt.output( 6 , 6 );
pt.output(); // 当pt去调用output方法时,this.x的this就代表当前对象pt
Point pt2 = new Point();
pt2.output( 5 , 5 ); // 当pt2去调用output方法时,this.x的this就代表当前对象pt2
pt2.output();
}
}