java中static和this_理解Java中this和static的含义

//this:当前对象的引用

//在引用一个类的成员变量,this被编译器隐含传递过去

//this的用法

//返回当前对象的引用

//从一个构造函数中调用另外一个构造函数

//区分同名的成员变量和参数变量

//静态变量:类变量,为此类所有对象共享

//静态方法:静态方法里没有this引用

//不能在静态方法中访问非静态的成员变量和方法

//可以直接通过类访问静态成员,即使不存在该类的对象

package cn.edu.uibe.oop;

//this:当前对象的引用

//在引用一个类的成员变量,this被编译器隐含传递过去

//this的用法

//返回当前对象的引用

//从一个构造函数中调用另外一个构造函数

//区分同名的成员变量和参数变量

//静态变量:类变量,为此类所有对象共享

//静态方法:静态方法里没有this引用

//不能在静态方法中访问非静态的成员变量和方法

//可以直接通过类访问静态成员,即使不存在该类的对象

public class Point {

public double x; //X轴坐标

public double y; //Y轴坐标

public static int counter=0; //点的个数

public Point(){

this(1.0,1.0); //利用this调用其它构造方法

}

public Point(double x,double y){

this.x = x; //this.x是成员变量,x是参数变量

this.y = y;

counter++;

}

public Point plus(){

this.x++;

y++;

return this; //返回当前对象的引用

}

public void show(){

System.out.println("x="+x+" y="+y);

}

public static void showCounter(){

System.out.println("点的个数为:"+counter);

//x = 4; //不能访问实例变量

//this //没有this引用

//show(); //不能调用非静态的方法

}

public static void main(String[] args) {

Point p1;

p1 = new Point();

Point p2 = new Point(3,3);

p2.plus();

p1.show();

Point p3 = p1.plus(); //p3和p1指向了同一个对象

if(p1==p3){

System.out.println("p1=p3");

}

p1.plus().plus().plus();

p1.show();

p2.show();

System.out.println(Point.counter);

Point.showCounter(); //通过类名调用静态方法

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值