JAVA基础-U7 面向对象编程(基础部分)-this

this

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrkQBEQw-1685258042726)(C:/Users/苏逸云/AppData/Roaming/Typora/typora-user-images/image-20230525153253754.png)]

public class This01{
	public static void main(String[] args){
		Dog dog = new Dog("doby", 3);
		System.out.println("doby.harshCode:\t" + dog.hashCode());
	}
}

class Dog{
	String name;
	int age;
	public Dog(String name, int age){
		this.name = name;
		this.age = age;
		System.out.println("this.hashCode:\t" + this.hashCode());
	}
}
this.hashCode:  366712642
doby.harshCode: 366712642
  1. java虚拟机会给每个对象分配this,代表当前对象。
  2. 简单地说,哪个对象调用,this就代表哪个对象

注意事项和使用细节
  1. this关键字可以用来访问本类的属性、方法、构造器

  2. this用于区分当前类和局部变量

  3. 访问成员方法的语法:this.方法名(参数列表)

    class T{
        public void f1(){}
        public void f2(){
            f1();//1
            this.f1();//2
            //两种方法任选一种
        }
    }
    
  4. 访问构造器语法:this(参数列表),注意只能在构造器中使用,且要放在第一行

    class T{
        public T(){
            this("jack", 100);//这里调用了T(String name, int age)构造器
            System.out.println("T()");
        }
        public T(String name, int age){
            System.out.println("T(String name, int age)");
        }
    }
    
    T t = new T();
    
    T(String name, int age)
    T()
    
  5. this不能在类定义的外部使用,只能在类定义的方法中使用


练习

定义Person类,里面有name,age属性,并提供compareTo比较方法,用于判断是否和另一个人相等

public class This03{
	public static void main(String[] args){
		Person p1 = new Person("Amy", 20);
		Person p2 = new Person("Emliy", 20);
		System.out.println(p1.compareTo(p2));
	}
}

class Person{
	String name;
	int age;
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	public boolean compareTo(Person p){
		return this.name.equals(p.name) && this.age == p.age;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值