this关键字

this 指代的就是当前对象

JavaSE-31-1

  • this 修饰属性

    当属性名字和形参发生重名的时候,或者属性名字和局部变量重名的时候,都会发生就近原则,所以如果直接使用变量名字的话就指的是离的近的那个形参或者局部变量,这时候如果想要表示属性的话,在前面要加上 this 修饰

    public class Person {
        int age;
        public Person(){}
        public Person(int age){
            this.age = age;
        }
    }
    
  • this 修饰方法

    在同一个类中,方法可以互相调用,this 可以省略不写

    public class Person {
        public void play(){
            /*this.*/eat();
            System.out.println("上网");
            System.out.println("洗澡");
        }
        public void eat(){
            System.out.println(age);
            System.out.println("吃饭");
        }
    }
    
  • this 修饰构造器

    同一个类中的构造器可以相互用 this 调用,注意 this 修饰构造器必须放在第一行

    public class Person {
        int age;
        String name;
        double height;
        public Person(){}
        public Person(int age,String name,double height){
            this(age,name);
            this.height = height;
        }
        public Person(int age,String name){
            this(age);
            this.name = name;
        }
        public Person(int age){
            this.age = age;
        }
    }
    

Static关键字

  • static 修饰属性,推荐通过 类名.属性名 的方式去访问

    public class Test {
        int id;
        static int sid;
    }
    public static void main(String[] args) {
        System.out.println(Test.sid);
    }
    

    在类加载的时候,会将静态内容也加载到方法区的静态域中。静态的内容先于对象存在,这个静态内容被所有该类的对象共享。

  • static 修饰方法

    public class Demo {
        int id;
        static int sid;
        public void a(){
            System.out.println(id);
            System.out.println(sid);
            System.out.println("------a");
        }
        static public void b(){
            //System.out.println(this.id); //在静态方法中不能使用this关键字
            //a(); //在静态方法中不能访问非静态的方法
            //System.out.println(id); //在静态方法中不能访问非静态的属性
            System.out.println(sid);
            System.out.println("------b");
        }
        public static void main(String[] args) {
            Demo d = new Demo();
            d.a();
            Demo.b();
            d.b();
            b();
        }
    }
    
    

    有几点需要注意的:

    • staticpublic 都是修饰符,并列的没有先后顺序,先写谁后写谁都行
    • 在静态方法中不能使用 this 关键字
    • 在静态方法中不能访问非静态的方法
    • 在静态方法中不能访问非静态的属性
    • 静态方法推荐用 类名.方法名 的方式调用(也可以用 对象名.方法名 ,在同一个类中还可以直接调用)