1. Protected keyword
Protected is an access modification qualifier, and the properties and methods modified by it can be accessed in subclasses, even in different packages.
father:
// 为了掩饰基类中不同访问权限在子类中的可见性,为了简单类B中就不设置成员方法了
// extend01包中
class B {
private int a;
protected int b; // 被protected修饰
public int c;
int d;
}
}
Subclasses in the same package can access the properties/methods modified by protected
// extend01包中
// 同一个包中的子类
class D extends B{
public void method(){
// super.a = 10; // 编译报错,父类private成员在相同包子类中不可见
super.b = 20; // 父类中protected成员在相同包子类中可以直接访问
super.c = 30; // 父类中public成员在相同包子类中可以直接访问
super.d = 40; // 父类中默认访问权限修饰的成员在相同包子类中可以直接访问
}
}
Subclasses in different packages can access the properties/methods modified by protected
// extend02包中
// 不同包中的子类
class C extends B {
public void method(){
// super.a = 10; // 编译报错,父类中private成员在不同包子类中不可见
super.b = 20; // 父类中protected修饰的成员在不同包子类中可以直接访问
super.c = 30; // 父类中public修饰的成员在不同包子类中可以直接访问
//super.d = 40; // 父类中默认访问权限修饰的成员在不同包子类中不能直接访问
}
}
Ordinary classes in different packages cannot access properties/methods modified by protecte d
// extend02包中
// 不同包中的类
class TestC {
public static void main(String[] args) {
C c = new C();
c.method();
// System.out.println(c.a); // 编译报错,父类中private成员在不同包其他类中不可见
// System.out.println(c.b); // 父类中protected成员在不同包其他类中不能直接访问
System.out.println(c.c); // 父类中public成员在不同包其他类中可以直接访问
// System.out.println(c.d); // 父类中默认访问权限修饰的成员在不同包其他类中不能直接访问
}
}
Two, the final keyword
1. Attributes modified by final cannot be modified
final int a = 20;
a = 100;//编译出错
2. The method modified by final cannot be rewritten
In polymorphism will introduce
2. A class modified by final cannot be inherited (sealed class)
final class A {
int a;
}
class B extends A{ //编译出错
}