package test06;
public class PermissionModel { private int age; public String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package test06;
public class PermissionTest {
public static void main(String[] args) { PermissionModel p=new PermissionModel(); p.getAge(); p.setAge(12); p.getName(); p.setName("wang"); p.name="wangsong";//public 方法可以在类外部访问 p.age=12;//这个方法是错误的,私有方法,只能在类内部访问 } //public 可以直接访问这个类内部的元素 public void setName(){ new PermissionModel().name="li"; } }
访问权限的控制加强了具体实现的隐藏
定制自己的工具库取代输出
package test06.util;
import java.util.Locale;
public class Print {
public static void print(boolean b){ System.out.print(b); } public static void print(char c){ System.out.print(c); } public static void print(char []s){ System.out.print(s); } public static void print(double d){ System.out.print(d); } public static void print(float f){ System.out.print(f); } public static void print(int i){ System.out.print(i); } public static void print(long l){ System.out.print(l); } public static void print(String s){ System.out.print(s); } public static void printf(Locale l,String format,Object args){ System.out.printf(l, format, args); } public static void println(){ System.out.println(); } public static void println(boolean b){ System.out.println(b); } public static void println(char c){ System.out.println(c); } public static void println(char []s){ System.out.println(s); } public static void println(double d){ System.out.println(d); } public static void println(float f){ System.out.println(f); } public static void println(int i){ System.out.println(i); } public static void println(long l){ System.out.println(l); } public static void println(Object obj){ System.out.println(obj); } public static void println(String s){ System.out.println(s); } }
用static引入包
package test06;
import static test06.util.Print.*;
public class Hello { public static void main(String[] args) { print("Hello World!"); } }