当前位置:网站首页>方法的重写
方法的重写
2022-08-04 18:08:00 【弱冠初心】
方法重写或方法的覆盖(overriding)
- 子类根据需求对从父类继承的方法进行重新编写
- 重写时,可以用super.方法的方式来保留父类的方法
- 构造方法不能被重写
父类:Person
子类: Pupil
public class Person {
String name;//父类属性
String age;//父类属性
//父类有参构造方法
public Person(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String names(){
return name;
}
//打印信息,自我介绍
void personInfo(){
System.out.print("我叫"+this.name+",今年"+this.age);
}
public Person() {
super();
}
//重写toString()方法
@Override
public String toString() {
return "我叫:"+this.name+"今年:"+this.age;
}
//重写equals()方法
public boolean equals(Pupil pup) {
if(pup.name.equals(this.name )){
return true;
}else{
return false;
}
}
//子类继承父类
public class Pupil extends Person {
String pupilStudent;//子类特有的属性
//子类构造方法
public Pupil(String name, String age, String pupilStudent) {
super(name, age);
this.pupilStudent = pupilStudent;
}
//重写父类打印语句,自我介绍
@Override
void personInfo() {
super.personInfo();//调用父类方法
System.out.print(" ,我是小学生");
}
//mian方法,进行测试
public static void main(String[] args) {
Pupil pup = new Pupil("苏雨", "18岁", " ");
pup.personInfo();
System.out.println(pup);
System.out.println(pup.toString());
Pupil pup2 = new Pupil("苏雨", "18岁", " ");
System.out.println(pup.equals(pup2));
}
方法重写的原则:
重写与重载之间的区别 :从下面两张图理解
Object类被子类经常重写的方法
方法 | 说明 |
toString() | 返回当前对象本身的有关信息,按字符串对象返回 |
equals() | 比较两个对象是否是同一个对象,是则返回true |
hashCode() | 返回该对象的哈希代码值 |
getClass() | 获取当前对象所属的类信息,返回Class对象 |
边栏推荐
猜你喜欢
OpenInfra Days China 2022|SelectDB与你共享 Apache Doris 在互联网广告业务中的实践
解决错误:The package-lock.json file was created with an old version of npm
报道称任天堂在2023年3月前不会推出任何新硬件产品
Flask框架实现注册加密功能详解【Flask企业课学习】
Matlab drawing 1
DHCP&OSPF combined experimental demonstration (Huawei routing and switching equipment configuration)
基于大学生内卷行为的调查研究
Matlab画图1
关于ETL的两种架构(ETL架构和ELT架构)
EasyCVR如何通过接口调用设备录像的倍速回放?
随机推荐
企业即时通讯软件有哪些功能?对企业有什么帮助?
LeetCode 899. 有序队列
OpenInfra Days China 2022 | SelectDB to share with you the Apache Doris in Internet advertising business practices
【MySQL】数据库的4中隔离级别
Matlab画图1
Interval greedy (interval merge)
Boosting之GBDT原理
Thrift IDL Sample File
Web端即时通讯技术:WebSocket、socket.io、SSE
离散化求前缀和
使用bash语句,清空aaa文件夹下的所有文件
离线同步odps到mysql 中文乱码是因为?mysql已是utf8mb4
Cholesterol-PEG-DBCO,CLS-PEG-DBCO,胆固醇-聚乙二醇-二苯基环辛炔科研试剂
如何让 JS 代码不可断点
容器化 | 在 NFS 备份恢复 RadonDB MySQL 集群数据
数仓建模面试
Speech Recognition Learning Resources
Thrift installation configuration
Alibaba Cloud International Edition uses ROS to build WordPress tutorial
区间贪心(区间合并)