.................

重写和重载的区别:

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 2023-05-03 16:37  么么^  阅读(200)  评论(0编辑  收藏  举报

Live2D