Java核心技术第五章 继承 笔记

本文详细介绍了Java中final关键字的用法,包括阻止类被继承和方法被重写,以及如何使用final修饰变量。此外,还深入探讨了equals方法的正确实现方式,包括如何进行对象身份比较和类型检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 阻止继承:final类和final方法

使用关键字final定义的类不允许被继承

使用关键字final定义的方法不允许被子类覆盖,final类中的方法自动为final方法

成员变量如果被声明为final,则构造对象后不允许改变它们的值。对于final类,成员变量不会自动final

 

2. 控制可见性的4个访问修饰符

1)仅对本类可见——private
2)对本包可见——默认
3)对本包和所有子类可见——protected
4)对所有类可见——public

3. equals方法
该方法用于判断两个对象是否相当,可重写该方法
class Employee {
  public boolean equals(Object otherObject) {
  //a quick test to see if the objects are identical
  if(this == otherObject) {
   return true;
  }

  //must return false if the explicit parameter is null
  if(otherObject == null) {
   return false;
  }

  //if the classes don't match, they can't be equal
  if(getClass() != otherObject.getClass()) {
   return false;
  }
  
  //check whether otherObject is Employee
  if(!(otherObject instanceof Employee) {
   return false;
  }

  //now we know otherObject is a non-null Employee
  Employee other = (Employee) otherObject;
  
  //test whether the fields have identical values
  return name.equals(other.name) && salary==other.salary && hireDay.equals(other.hireDay);
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值