标签:
7 复用类
7.1 组合
即在一个类中使用另一个类作为成员变量,这是复用了现有程序代码的功能,而非形式。
7.2 继承
1 package com.chenlei.study.thinkinginjava; 2 3 import static com.chenlei.study.thinkinginjava.Print.*; 4 5 public class ClassConstructor { 6 7 public static void main(String[] args) { 8 new C(); 9 } 10 11 } 12 13 class A{ 14 public A() { 15 print("A constructor"); 16 } 17 } 18 19 20 class B extends A{ 21 private int flag; 22 public B(int flag) { 23 this.flag = flag; 24 print("B constructor"); 25 } 26 } 27 28 class C extends B{ 29 public C() { 30 super(0);//如果不指定调用哪个父类构造器将无法通过编译,由此可见在基类构造器被调用之前一定会调用父类构造器 31 } 32 } 33 /** 34 * output: 35 * A constructor 36 * B constructor 37 */
7.3 代理
1 package com.chenlei.study.thinkinginjava; 2 3 public class Proxy { 4 public static void main(String[] args) { 5 BossProxy proxy = new BossProxy(); 6 Print.print(proxy.getEmployeeNum()); 7 } 8 } 9 10 abstract class CompanyMember{ 11 private int age; 12 private String name; 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 public String getName() { 20 return name; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 } 26 27 class Boss extends CompanyMember{ 28 private double money;//不能让员工知道 29 private int employeeNum; 30 private int wifeNum;//不能让员工知道 31 32 Boss(double money,int employeeNum,int wifeNum){ 33 this.money = money; 34 this.employeeNum = employeeNum; 35 this.wifeNum = wifeNum; 36 } 37 38 public double getMoney() { 39 return money; 40 } 41 public void setMoney(double money) { 42 this.money = money; 43 } 44 public int getEmployeeNum() { 45 return employeeNum; 46 } 47 public void setEmployeeNum(int employeeNum) { 48 this.employeeNum = employeeNum; 49 } 50 public int getWifeNum() { 51 return wifeNum; 52 } 53 public void setWifeNum(int wifeNum) { 54 this.wifeNum = wifeNum; 55 } 56 } 57 58 class BossProxy extends CompanyMember{ 59 private Boss boss; 60 public BossProxy() { 61 if(boss == null){ 62 boss = new Boss(1000d,100,3); 63 } 64 } 65 public int getEmployeeNum(){ 66 return boss.getEmployeeNum(); 67 } 68 }
由此可见,代理让一些该暴露的暴露了,不该暴露的隐藏起来,这似乎在权限管理中非常有用。虽然没看过设计模式中的代理模式,但是我觉得可以在代理方法前后包裹一些方法和操作来做特定的处理,比如springAOP、spring事务代理?或者是实现同步锁的时候在原子方法保证安全性?懒加载(spring注入)?
7.4 基类中重载
在基类中重载父类的方法是可以的,只要基类的重载方法满足方法名和父类某些方法相同,但参数列表个数、顺序、类型或返回类型不同时都是可以正常重载的,若方法名和返回类型、参数列表一模一样,将是覆盖,而不是重载。
7.5 组合和继承的区别
7.6 protected关键字
7.7 向上转型
一个通用的方法需要对一种类型的对象进行处理,继承的优势就显现出来了;只需要将参数设置为基类,那么任何该基类的子类都可以作为参数传入而不报错,因为编译器将把这些子类自动转型为基类,而不需要为每个子类写一个方法,便于管理和操作。
7.8 final关键字
1 package com.chenlei.study.thinkinginjava; 2 3 public class Final { 4 public String string = "haha"; 5 public final String aString = string; 6 public static void main(String[] args) { 7 Final final1 = new Final(); 8 final1.string = "123"; 9 System.err.println(final1.aString); 10 } 11 } 12 /** 13 * output: 14 * haha 15 */
标签:
原文地址:http://www.cnblogs.com/Vabshroo/p/tkij-ch7.html