Java——this和static关键字

this关键字

编译器优化:就近原则,取最近的同变量名

1 this表示调用本类属性
只要在类中访问类的属性,一定要加上this关键字

2 this表示调用本类方法
a.调用普通方法: this.方法名(参数)
当有类的继承关系时,调用本类方法时一定要加this关键字
b.调用构造方法: this(参数)

注意:
1> this调用构造方法必须放在构造方法首行
2> this调用构造方法不允许成环

eg:
public Person(){
System.out.println("*******");
}
public Person(String name){
this();
this.name=name;
}
public Person(String name,int age){
this(name);
this.age=age;
}

3 this表示当前对象

static关键字:

1.static变量——类属性(静态属性)
static属性称为类属性,保存在全局数据区中(方法区——所有对象共享区域),通过类名调用,与对象实例化无关,有默认值。
描述共享属性使用static属性(使用频率少)

2.static方法——类方法(静态方法)
通过类名调用,与对象实例化无关。常见工具类方法

Person.fun();
类似:数组方法
Arrays.sort(数组名);
arraycopy();

注意:
1-> 局部变量不可用static修饰
2-> private,static不可用于外部类,但可用于内部类

猜你喜欢

转载自blog.csdn.net/S_Sandra/article/details/83821518
今日推荐