方法的覆写
类和父类有相同的方法,那么类中方法的访问权限不能比父类中对应方法的访问权限严格,这就叫方法的覆写,一般称之为类覆写了父类中的某个方法
覆写方法的作用:对于一个类,向上转换后(把类的实例化对象赋值给类的父类的对象),通过该父类的对象直接访问该父类的对象的本类部分中被类所覆写的方法时,将自动访问跳转到类中对应的覆写的方法
static方法的覆写不起覆写作用,原因现阶段只能解释为Java就是这样设计的
package test1; public class Test1 { public static void main(String[] args){ Person per=new Student(); per.funx(); } } class Person{ private void fun(){ System.out.println("Person的fun方法"); } public void funx(){ this.fun(); } } class Student extends Person{ private static void fun(){ System.out.println("Student的fun方法"); } }
输出结果为: Person的fun方法
private方法的覆写不起覆写作用,因为private方法都是通过间接访问的
package test1; public class Test1 { public static void main(String[] args){ Person per=new Student(); per.funx(); } } class Person{ private void fun(){ System.out.println("Person的fun方法"); } public void funx(){ this.fun(); } } class Student extends Person{ private static void fun(){ System.out.println("Student的fun方法"); } }
输出结果为: Person的fun方法
来源:itnose