this关键字
this 的作用:
this 表示的是当前对象本身 更准确的说,this代表当前对象的一个引用
普通方法中的this:
- 区分类成员属性和方法的形参
- 位置:任意
构造方法中的this:
- 使用this 来调用其他构造方法
- 位置:必须是第一条语句
public class TestThis {
int a ,b,c; //成员变量
TestThis(int a,int b ){
this.a = a;//区分了成员变量和局部变量
this.b = b;//this 的常用情况
}
TestThis(int a,int b,int c){
this(a,b); //调用构造方法,必须放在第一句
this.c = c;
}
void sing(){
}
void dance(){
sing(); //调用本类中的sing()
System.out.println("边唱歌边跳舞");
}
public static void main(String[] args){
TestThis stu = new TestThis(2,3);
stu.dance();
}
}
注意:static方法中不能用this
static关键字
static修饰的成员变量和方法,从属于类;普通变量和方法从属于对象
在类中,static声明的成员变量为静态成员变量,也称类变量 否则称为实例变量
实例变量和类变量(静态变量)区别:
1.不同对象的实例变量互不相同
2.所有对象共享类变量
3.通过类名直接访问类变量 类变量不仅可以通过某个对象访问,也可以直接用过类名访问
实例方法和类方法(静态方法)区别:
1.对象调用实例方法 实例方法中不仅可以操作实例变量也可操作类变量
2.类名调用类方法 实例方法不能通过类名调用,只能通过对象 类方法不可以操作实例变量
public class StaticTest {
int id;
String name;
String pwd;
static String company ="hp";
public StaticTest(int id ,String name){
this.id = id;
this.name =name;
}
public void login(){
printCompany();//实例方法可调用静态方法
System.out.println("company");
System.out.println("登陆"+name);
}
public static void printCompany(){
// login(); //调用非静态方法报错
System.out.println(company);
}
public static void main(String[] args){
StaticTest stu = new StaticTest(10001,"lee");
stu.printCompany();
stu.company="京东";
stu.printCompany();
}
}
本文仅用于自我学习,如有错误请指出,谢谢!