当前位置:网站首页>方法的重写
方法的重写
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对象 |
边栏推荐
猜你喜欢

基于 eBPF 的 Kubernetes 可观测实践

Iptables防火墙基础知识介绍

企业即时通讯软件有哪些功能?对企业有什么帮助?

OpenInfra Days China 2022 | SelectDB to share with you the Apache Doris in Internet advertising business practices

Develop those things: How to obtain the traffic statistics of the monitoring site through the EasyCVR platform?

Flink / Scala - 使用 RedisSink 存储数据

2022年五一数学建模C题讲解

"No title"

自己经常使用的三种调试:Pycharm、Vscode、pdb调试

"Involution" Index Analysis Based on AHP
随机推荐
DOM Clobbering的原理及应用
Cholesterol-PEG-DBCO,CLS-PEG-DBCO,胆固醇-聚乙二醇-二苯基环辛炔科研试剂
darknet源码阅读笔记-02-list.h和lish.c
dotnet core 输出调试信息到 DebugView 软件
How to make JS code unbreakable
八猴渲染器是什么?它能干什么?八猴软件的界面讲解
ptables基本语法使用规则
Error when using sourcemap for reporting an error: Can‘t resolve original location of error.
悦刻难回巅峰
Flask框架实现注册加密功能详解【Flask企业课学习】
情绪的波动起伏
22/8/4 记忆化搜索+博弈论
【软件工程之美 - 专栏笔记】37 | 遇到线上故障,你和高手的差距在哪里?
【web自动化测试】playwright安装失败怎么办
自己经常使用的三种调试:Pycharm、Vscode、pdb调试
Hezhou Cat1 4G module Air724UG is configured with RNDIS network card or PPP dial-up, and the development board is connected to the Internet through the RNDIS network card (taking the RV1126/1109 devel
OpenInfra Days China 2022 | SelectDB to share with you the Apache Doris in Internet advertising business practices
After EasyCVR is locally connected to the national standard device to map the public network, the local device cannot play and cascade the solution
解决错误:The package-lock.json file was created with an old version of npm
How to recruit programmers