.................
随笔 - 31  文章 - 0  评论 - 0  阅读 - 4511

重写和重载的区别:

1.重写和重载的区别:
a.重载:
1.java中同一个类中,方法名相同,参数列表不同的同名方法
这叫重载。
2.要求俩个方法方法名相同,参数列表不同,
参数列表不同包括:参数的个数不同,参数的类型不同,参数类型位置不同
3.目的:为了让方法接收不同参数时实现不同功能。典型的是多态

b.重写:
1.重写出现在子类继承父类时,子类对父类方法实现细节的重新定义

2.子类重写父类方法时,不能降低访问权限,可以扩大访问权限
public class Father{
protected void test1(){
System.out.println("father test1")
}

}
//不能将访问权限降为private
public class Son extends Father{
private void test1(){
System.out.println("Son test1")
}
}
//只能public或者protected
public class Son extends Father{
public void test1(){
System.out.println("Son test1")
}
}

3.父类private与final修饰的方法不能被子类重写

4.子类重写父类方法,在处理异常时,只能抛出父类异常的全集,子集或空集
public class Father{
protected void test1() throws NullPointerException,NumberFormatException{
System.out.println("father test1")
}

}
public class Son extends Father{
1.可以没有异常抛出(空集)
protected void test1(){
System.out.println("father test1")
}
2.可以抛出父类异常子集
protected void test1() throws NullPointerException{
System.out.println("father test1")
}
2.可以抛出父类异常全集
protected void test1() throws NullPointerException,NumberFormatException{
System.out.println("father test1")
}

}

5.重写方法返回值,可以缩小返回类型范围,但不可以扩大返回类型范围

posted on   么么^  阅读(311)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Live2D
点击右上角即可分享
微信分享提示