Object类

本人对于Object类的总结
1.Object类是所有java类中的父类
2.如果在类的声明中没有使用extends关键字指明其父类,则默认父类为java.lang.Object类
3.Object类中没有属性只有方法.常用的方法有
①getClass 返回对象的类型

public static void main(String[] args) {
		Student student =new Student("曹操", 42, "男性", "山东");
		Student student1 =new Student("曹丕", 22, "男性", "山东");
		System.out.println(student1.getClass());
		System.out.println(student.getClass());
	}
	
  ②hashCode 哈希值是使用哈希算法得到的一个整数,可以看做是对象的唯一标记 【默认使用的是地址值进行计算】
public static void main(String[] args) {
		Student student =new Student("曹操", 42, "男性", "山东");
		Student student1 =new Student("曹丕", 22, "男性", "山东");
		Student student3 =new Student("曹丕", 22, "男性", "山东");
		//不同对象的哈希值基本上是不同的
		System.out.println(student.hashCode());
		System.out.println(student1.hashCode());
		System.out.println(student3.hashCode());
	}
重写hashCode方法,使用属性计算哈希值
```java

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		return result;
	}
	//重写之后的hashCode值是相同的
  ③toString     返回对象的字符串表示形式【拼接对象中的所有属性】
/**
	 * 返回对象的字符串表示形式,拼接的是所有的属性
	 */
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age
		 + ", sex=" + sex + ", address=" + address + "]";
	}
	
  ④equals       比较两个对象是否相等【默认比较的是地址值】重写equals方法比较的是两个属性         
@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		return true;
	}
 ⑤finalize 最终的方法:对象在被当做垃圾回收之前执行的最后一个方法
@Override
	protected void finalize() throws Throwable {
		//对象被当做垃圾回收之前执行的最后一个方法
		System.out.println(name+"被当做垃圾回收");
	}
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值