编程语言
首页 > 编程语言> > Java学习笔记——this

Java学习笔记——this

作者:互联网

问题引入

package ThisDemo;

public class ThisTest {
    public static void main(String[] args) {
        Person person = new Person("as",19);
        person.print();
    }
}

class Person{
    String name;
    int age;

    public Person(String name,int age){
        name = name;
        age = age;
    }

    public void print(){
        System.out.println(name + " " + age);
    }
}

结果

null 0

问题分析

原本是想将构造器的形参,直接写成属性名,但是由于变量的作用域原则,构造器的name和age是局部变量,不是属性,在print()中调用的是属性,所以会出现null 0的结果

解决方法

用this

this

使用细节

用例

package ThisDemo;

public class TestPerson {
    public static void main(String[] args) {
        Person1 person1 = new Person1("aaa",19);
        Person1 person2 = new Person1("bbb",18);
        Person1 person3 = new Person1("aaa",19);
        System.out.println(person1.compareTo(person2));
        System.out.println(person1.compareTo(person3));
    }
}

class Person1{
    String name;
    int age;

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

    public boolean compareTo(Person1 person1){
        return this.name.equals(person1.name) && this.age == person1.age;
    }
}

标签:Java,name,age,person1,笔记,学习,Person1,public,String
来源: https://blog.csdn.net/weixin_46324286/article/details/120513672