this关键字
this指的是当前实例对象,可以在构造方法内部区分同名的成员变量和局部变量
可以用于调用构造方法,减少代码冗余。(在构造方法中通过this调用其他构造方法
的语句必须是第一句),this也可以调用成员属性和成员方法
class Person{
String name;
int age;
String address;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public Person(String name,int age,String address){
this(name,age);
this.address=address;
}
void hello(){
System.out.println("hello....");
}
void introduce(){
this.hello();
}
}
static关键字
表示静态的,可以修饰变量和方法,可以通过类名直接调用
修饰成员变量时,称为静态变量,或者类变量;
修饰方法时,称为静态方法,或者类方法。
*静态变量不会存储在实例对象中,举个例子
class Calculator(){
static int num1=1;
int num2=2;
void a1(){
num1=8;
num2=8;
}
}
public static void main(String[] args){
Calculator c1=new Calculator();
Calculator c2=new Calculator();
c1.a1;
System.out.println("num1"+c2.num1);
System.out.println("num2"+c2.num2);
}
一个类中的static成员在该类被使用的时候就被分配空间并赋值,初始值为null或者0。
class A(){
static A ins =new A(1);
static int num1=5;
int num2;
A(int num3){
num2=num1-num3;
}
}
public static void main(String[] args){
System.out.println(A.ins.num2);
System.out.println(new A(1).num2);
}
分析,第一个打印直接使用A类的ins静态变量,在使用A类的时候给static的成员分配空间
(数值型默认为0,其他默认为null),ins需要使用A的构造方法,把num3的值传进去,执行语句
num2=num1-num3=0-1=-1
第二个打印直接new了一个A对象,会先给这个对象分配空间并赋值,就是正常得出4的结论
//静态方法使用注意事项
在实例方法中调用静态方法(属性)时可编译的
而在静态方法中调用实例方法(属性)时是不行的,因为不能保证静态方法调用时存在实例方法
谨慎静态使用static,其生命周期过长
在静态方法中不能使用this关键字
举个例子
class A(){
int age;
void mA(){
age=20;
}
static void mb(){
age=10;
}
}