Java继承之方法重写

文章介绍了Java编程中的方法重载和重写概念。方法重载要求方法名称相同但参数列表不同,而方法重写则需在子类中保持与父类相同的方法名称、参数列表和返回值,但实现不同的功能。重写方法不能降低访问权限,并且可以通过super关键字调用父类被重写的方法。示例代码展示了如何在子类Student中重写父类Person的printInfo方法。

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

概念

重载(方法名称一样,参数列表不一样)
重写(完成做到重写,都一样,实现功能不一样)

  • 方法重写是指子类可以根据需要对父类继承来的方法进行改写,是多态机制的前奏。

注意点

  • 重写方法必须和被重写方法具有相同的方法名称、参数列表和返回值
  • 重写方法不能比被重写方法有更加严格的访问权限
  • 父类中的私有方法,不能被重写
  • 在子类重写的方法中继续使用父类被重写的方法可以通过super.函数名获取

代码如下

package jicheng.dzz.java;

class Person{
	String name;
	String address;
	
	public void printInfo(){
		System.out.println("父类name=" + name);
	}
	public void printAddr(){
		System.out.println("父类address=" + address);
	}
}

// 重写方法必须和被重写方法具有相同的方法名称、参数列表和返回值
class Student extends Person{
	int score;
	public void printInfo(){
		super.printInfo();
		System.out.println("子类打印name=" + name);
	}
}

public class Test {
	public static void main(String[] args) {
		Student s = new Student();
		s.name = "张";
		s.printInfo();
	}
}

运行结果

在这里插入图片描述

freadahead.c: In function 'freadahead': freadahead.c:92:3: error: #error "Please port gnulib freadahead.c to your platform! Look at the definition of fflush, fread, ungetc on your system, then report this to bug-gnulib." 92 | #error "Please port gnulib freadahead.c to your platform! Look at the definition of fflush, fread, ungetc on your system, then report this to bug-gnulib." | ^~~~~ make[7]: *** [Makefile:1910: freadahead.o] Error 1 make[7]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit/build_dir/host/m4-1.4.18/lib' make[6]: *** [Makefile:1674: all] Error 2 make[6]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit/build_dir/host/m4-1.4.18/lib' make[5]: *** [Makefile:1572: all-recursive] Error 1 make[5]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit/build_dir/host/m4-1.4.18' make[4]: *** [Makefile:1528: all] Error 2 make[4]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit/build_dir/host/m4-1.4.18' make[3]: *** [Makefile:29: /home/wk/lede_AR9331_zhuotk_source_64bit/build_dir/host/m4-1.4.18/.built] Error 2 make[3]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit/tools/m4' make[2]: *** [tools/Makefile:150: tools/m4/compile] Error 2 make[2]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit' make[1]: *** [tools/Makefile:146: /home/wk/lede_AR9331_zhuotk_source_64bit/staging_dir/target-mips_24kc_musl/stamp/.tools_compile_yynyyyyynyyyyynyynnyyyyyyyyyyyyyyyyyyyynyynynyyyynny] Error 2 make[1]: Leaving directory '/home/wk/lede_AR9331_zhuotk_source_64bit' make: *** [/home/wk/lede_AR9331_zhuotk_source_64bit/include/toplevel.mk:209:world] 错误 2
最新发布
04-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值