说说你对关键字this的认识?

共有三种用法。

1.        this.属性名

public class Teacher {
    private String name;
    private int age;
    private int salary;

    public Teacher(String name, int age, int salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }


    public static void main(String[] args) {
        Teacher wang_teacher = new Teacher("王",18,10000);
    }
}

this表示当前对象(wang_teacher) .也可以翻译成“的”的意思。

2.        this.方法名

public class Dog {
    public void jump(){
        System.out.println("狗在跳!");
    }
    public void run(){
        this.jump();
        System.out.println("狗在跑!");
    }
    public static void main(String[] args) {
        Dog dahuang = new Dog();
        dahuang.run();
    }
}

//狗在跳!
//狗在跑!

这里可以看到,main函数只创建了一个对象dahuang,如果不用this.方法名又会怎样呢?

public class Dog {
    public void jump(){
        System.out.println("狗在跳!");
    }
    public void run(){
        Dog xiaohei = new Dog();
        xiaohei.jump();
        System.out.println("狗在跑!");
    }
    public static void main(String[] args) {
        Dog dahuang = new Dog();
        dahuang.run();
    }
}

如果不用this.方法名,你又引入一个对象,xiaohei,可我明明想让dahuang在run函数中调用dahuang的jump函数,结果是xiaohei在跳,dahuang在跑。

所以说,this 可以代表任何对象,当 this 出现在某个方法体中时,它所代表的对象是不确定的,但它的类型是确定的,它所代表的只能是当前类的实例。只有当这个方法被调用时,它所代表的对象才被确定下来,谁在调用这个方法,this 就代表谁。

但是我还可以这样写:

public class Dog {
    public void jump(){
        System.out.println("狗在跳!");
    }
    public void run(){
        jump();
        System.out.println("狗在跑!");
    }
    public static void main(String[] args) {
        Dog dahuang = new Dog();
        dahuang.run();
    }
}

我直接在run函数中调用了jump方法,省略了调用 jump() 方法之前的 this,但实际上这个 this 依然是存在的。

最后:对于 static 修饰的方法而言,可以使用类来直接调用该方法,如果在 static 修饰的方法中使用 this 关键字,则这个关键字就无法指向合适的对象。所以,static 修饰的方法中不能使用 this 引用。并且 Java 语法规定,静态成员不能直接访问非静态成员。

3.this()访问构造方法

public class Student {
    private String name;

    public Student() {
        this("张三");
    }

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student.toString());
    }
}

//Student{name='张三'}

我main函数里边直接new Student(),创建了一个无参数的实例,但是无参数的构造方法使用了this(),并且给第二个带参数的构造方法传了“张三”这个参数,使得即使主函数没有传参,也能通过无参构造方法调用该实例的另外的构造方法。

注意:

  • this( ) 不能在普通方法中使用,只能写在构造方法中。
  • 在构造方法中使用时,必须是第一条语句。

你可能感兴趣的:(每日一问,java,开发语言)