一、访问修饰符
含义:修饰类、方法、属性,定义使用的范围
学习:
访问修饰符 本类 本包 其他包子类 其他包 private OK 默认的 OK OK protected OK OK OK public Ok OK OK Ok
- 经验:
a.属性没有特殊要求,就使用private修饰
b.属性如果要给子类使用,就使用protected修饰
c.方法如果要给子类重写,就使用protected修饰
d.方法没有特殊要求,就使用public修饰
二、private - 私有化(访问修饰符)
含义:私有化方法或属性
作用:
a.修饰属性:私有化属性,不能让外界使用
b.修饰方法:私有化方法,不能让外界使用应用场景:
a.不想让外界直接调用的属性就使用private修饰
b.不想让外界直接调用的方法就使用private修饰实例
package com.qf.test03;
public class Test01 {
public static void main(String[] args) {
A a = new A();
//a.attr;会报错,attr为类的私有化方属性,只能在类的内部调用,外界不能直接调用
//a.method1();会报错,method1()为类扥私有化方法,只能在类的内部调用,外界不能直接调用
a.method02();
}
}
package com.qf.test03;
public class A {
private String attr = "A类的私有化属性";
private void method01(){
System.out.println(this.attr);
System.out.println("A类的私有化方法");
}
public void method02(){
method01();
}
}