如果父类方法是private,子类方法是public,这样是覆盖还是新定义的方法?
package com.subclassoverrideparent;
import static java.lang.System.*;
public class Person {
private void fun(){
out.println("Person is fun");
}
public void print(){
this.fun();
}
}
package com.subclassoverrideparent;
import static java.lang.System.*;
public class Student extends Person {
public void fun(){
out.println("Student fun!");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Student().print();
}
}
输出结果:Person is fun
说明没有覆盖父类的fun方法,子类重新定义了一个新的fun方法;
如果:Person=>protected void fun()
Student=>public void fun()
则输出结果:Student fun!
父类fun()方法被子类覆盖了,结论:父类的private方法不允许被子类覆盖
如果都是public、protected、default,那当然是覆盖了;
如果父类是public,则子类不允许访问控制比public小,即不能是protected,private等,系统会提示错误。
final 方法不能覆盖,如果加static 修饰符,则调用时,调用的是父类的static方法.