封装
为什么要使用封装
提高代码的安全性。 提高代码的复用性。 “高内聚”:封装细节,便于修改内部代码,提高可维护性。 “低耦合”:简化外部调用,便于调用者使用,便于扩展和协作。
封装的实现
举个例子
package com. ssc. encapsulation. a ;
import com. ssc. test1. Test1 ;
public class Person {
private int testPrivate = 300 ;
int testDefault = 300 ;
protected int testProtect = 300 ;
public static void main ( String [ ] args) {
Person uPerson = new Person ( ) ;
uPerson. test ( ) ;
}
public void test ( ) {
System . out. println ( "这是Person类里面的方法" ) ;
System . out. println ( testDefault) ;
System . out. println ( testPrivate) ;
}
}
Student类(和Person类同一个包的子类)
package com. ssc. encapsulation. a ;
public class Student extends Person {
public static void main ( String [ ] args) {
Person person = new Person ( ) ;
person. testDefault = 311 ;
person. testProtect = 322 ;
person. test ( ) ;
}
}
Teacher类(和Person类不是一个包的子类)
package com. ssc. encapsulation. b ;
import com. ssc. encapsulation. a. Person ;
public class Teacher extends Person {
public static void main ( String [ ] args) {
Person uPerson = new Person ( ) ;
Teacher uTeacher = new Teacher ( ) ;
uPerson. test ( ) ;
uTeacher. test ( ) ;
}
public void test ( ) {
System . out. println ( super . testProtect) ;
}
}
protected属性的两个细节
若父类和子类在同一个包中, 子类可访问父类的 protected 成员,也可访问父类对象 的 protected 成员。 若子类和父类不在同一个包中,子类可访问父类的 protected 成员,不能访问父类对象 的 protected 成员
封装的使用细节
属性私有后, 提供相应的 get/set 方法来访问相关属性,这些方法通常是public 修饰的,以提供对属性的赋值与读取操作(注意:boolean 变量的 get方法是 is开头) 方法:一些只用于本类的辅助性方法可以用 private 修饰,希望其他类调用的方法用 public 修饰
package com. ssc. encapsulation ;
public class Javabean {
private int age;
private String name;
private boolean flag;
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
if ( age< 0 || age > 150 ) {
System . out. println ( "你输入的年龄不合法" ) ;
} else {
this . age = age;
}
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public static void main ( String [ ] args) {
Javabean uJavabean = new Javabean ( ) ;
uJavabean. setAge ( - 20 ) ;
System . out. println ( uJavabean. getAge ( ) ) ;
}
}