下表为Java访问控制符的含义和使用情况
类内部 | 本包 | 子类 | 外部包 | |
public | √ | √ | √ | √ |
protected | √ | √ | √ | × |
default | √ | √ | × | × |
private | √ | × | × | × |
继承:
public、protected修饰的方法可以被子类继承,同一个包下,默认的也可以被继承。
如果子类重写,要修改方法的访问权限,子类方法的访问权限必须比父类大。如下:父类方法为protected修饰,子类继承该方法并重写,可以定义public类型。
class parent{
protected void f1(){
System.out.println("parent f1()");
}
}
class Child extends parent{
public void f1(){
System.out.println("child f1()");
}
}
final修饰的方法无法被子类重写。
class parent{
//可以继承,但是无法被子类覆盖
public final void f2(){
System.out.println("parent f2()");
}
}
class Child extends parent{
//error
public void f2(){
System.out.println("child f2()");
}
}
final修饰的方法不可以被子类重写。区分是否是从父类继承过来的方法。
class parent{
//private修饰的方法不是父类的接口的一部分,无法被子类继承
private final void f3(){
System.out.println("parent f3()");
}
}
class Child extends parent{
//不是从父类继承的方法,仅仅是生成的新方法。
private final void f3(){
System.out.println("child f3()");
}
}
public class Person {
private void f(){
System.out.println("person");
}
public static void main(String[] args) {
Person p = new Chinese();
p.f();//调用父类的方法
}
}
class Chinese extends Person {
public void f(){//不是从父类继承过来的方法,是全新的。
System.out.println("chinese");
}
}
public class Person {
public static void main(String[] args){
Parent p = new Child();
//p.g();//error 父类中没有这个方法
}
}
class Parent{
void f(){
System.out.println("parent f()");
}
}
class Child extends Parent{
void f(){
System.out.println("child f()");
}
void g(){
System.out.println("child g()");
}
}
private属于final方法。