当前位置:网站首页>Day019 方法重写与相关类的介绍
Day019 方法重写与相关类的介绍
2022-08-05 04:15:00 【陌 年】
一、方法重写
1、方法重写的概念
(1)子类根据需求对从父类继承的方法进行重新编写
(2)重写时,可以用super.方法的方式来保留父类的方法
(3)构造方法不能被重写
2、方法重写规则
(1)方法名相同
(2)参数列表相同
(3)返回值类型相同或者是其子类
(4)访问权限不能严于父类
(5)父类的静态方法不能被子类覆盖为非静态方法,父类的非静态方法不能被子类覆盖为静态方法
(6)子类可以定义与父类同名的静态方法,以便在子类中隐藏父类的静态方法(注:静态方法中无法使用super)
(7)父类的私有方法不能被子类覆盖
(8)不能抛出比父类方法更多的异常
2、方法重写与方法重载的区别
二、Object类
Object类:是所有类的父类
Object类被子类经常重写的方法
1、Object类的equals()方法
(1)比较来俩个对象是否是同一个对象,是则返回true
(2)操作符
①简单数据类型,直接比较值。如1==2
②引用类型,比较两者是否为同一对象
注意:
(1)Object类的equals()方法与==没区别
(2)当有特殊需求,如认为属性相同即为同一对象时,需要重写equals()
(3)Java.lang.String重写了equals()方法,把equals()方法的判断变为了判断其值
2、练习
package cn.bdqn.demo04;
import java.util.Objects;
public class Student {
private String name;
private int idCard;
private int age;
public Student() {
}
public Student(String name, int idCard, int age) {
this.name = name;
this.idCard = idCard;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdCard() {
return idCard;
}
public void setIdCard(int idCard) {
this.idCard = idCard;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return idCard == student.idCard && age == student.age && Objects.equals(name, student.name);
}
}
package cn.bdqn.demo04;
import java.sql.SQLOutput;
public class Test {
public static void main(String[] args) {
Student stu1=new Student("张三",1234,22);
Student stu2=new Student("xx",1234,22);
System.out.println(stu1.equals(stu2));
}
}
边栏推荐
- 新人如何入门和学习软件测试?
- mutillidae下载及安装
- DEJA_VU3D - Cesium功能集 之 058-高德地图纠偏
- Bosses, I noticed that a mysql CDC connector parameters scan. The incremental. Sna
- bytebuffer 使用demo
- 36-Jenkins-Job Migration
- NPDP证书含金量高吗?跟PMP相比?
- [8.2] Code Source - [Currency System] [Coins] [New Year's Questions (Data Enhanced Edition)] [Three Stages]
- About the installation of sklearn library
- 虚证、实证如何鉴别?
猜你喜欢
随机推荐
新人如何入门和学习软件测试?
How do newcomers get started and learn software testing?
Event parse tree Drain3 usage and explanation
iMedicalLIS listener (2)
UE4 第一人称角色模板 添加冲刺(加速)功能
什么是ASEMI光伏二极管,光伏二极管的作用
The log causes these pits in the thread block, you have to guard against
Four-digit display header design
1007 Climb Stairs (greedy | C thinking)
【背包九讲——01背包问题】
DEJA_VU3D - Cesium功能集 之 056-智图Arcgis地图纠偏
关于sklearn库的安装
How to solve the three major problems of bank data collection, data supplementary recording and index management?
UE4 opens doors with overlapping events
[极客大挑战 2019]FinalSQL
[BJDCTF2020]EasySearch
Talk about 20 common problems in data governance
【树莓派】树莓派调光
Swing有几种常用的事件处理方式?如何监听事件?
[MRCTF2020]PYWebsite