封装
~
public class Demo01 {
public static int add( int a , int b ) {
return a + b;
}
public static void main(String[] args) {
System.out.println(1+1);
System.out.println(1+2);
System.out.println(1+3);
System.out.println(1+4);
System.out.println(1+5);
System.out.println(add(1,1));
System.out.println(add(1,2));
System.out.println(add(1,3));
System.out.println(add(1,4));
System.out.println(add(1,5));
}
}
~
上述案例:为了避免不断的+操作,把两数相加写入在add方法中,后续直接调用add方法。把具体的操作流程统一管理在add方法中,该过程就是封装的一种具体表现形式
访问权限修饰符
修饰符 | 同一个类 | 同一个包 | 子类 | 所有的类 |
---|---|---|---|---|
public 公有的 | √ | √ | √ | √ |
protected 受保护的 | √ | √ | √ | |
default 默认的 | √ | √ | ||
private 私有的 | √ |
类的封装
~
public class Demo02 {
// 把属性私有化
private String name;
private int age;
// 对外提供属性的设置方法
public void setName( String name) {
this.name = name;
}
// 对外提供属性的访问方法
public String getName() {
return this.name;
}
}
~
属性的访问权限尽量给的很小
对外单独提供访问方法
setName 给属性赋值
getName 读取属性的值
日志
使用过程
1 到log4j官网下载对应的软件包
2 解压,找到log4j.jar 压缩包
3 在Java项目中添加new directory 取名为lib ,将软件包粘贴在lib中
4 添加配置文件 在\apache-log4j-1.2.17\examples 中找到样例文件 *.properties,添加在项目中的资源配置目录下 resources