练习1:(2)创建一个简单的类。第二个类中,将一个引用定义为第一个类的对象。运用惰性初始化来实例化 这个对象。
package test; public class Manager { public static void main(String args[]){ Second s=new Second(); s.getFirst(); } /** * 打印结果: */ } class First{ } class Second{ First f; Second(){ System.out.println("Creating Second"); } First lazy(){ if(f==null){ System.out.println("Creating First"); f=new First(); } return f; } public First getFirst(){ return lazy(); } }
练习2:(2)从Detergent中继承产生一个新的类。覆盖scrub()并添加一个名为sterilize()的新方法。
package test; public class Manager { public static void main(String args[]){ Sub s=new Sub(); s.apply();s.dilute();s.foam();s.scrub();s.sterilize(); new print(s); } /** * 打印结果: Cleanser apply() dilute() foam() sub.scrub Detergent.scrub()sub.sterilize() */ } class print{ print(Object obj){ System.out.println(obj); } } class Cleanser{ private String s="Cleanser"; public void append(String a){ s+=a; } public void dilute(){ append(" dilute()"); } public void apply(){ append(" apply()"); } public void scrub(){ append(" scrub() "); } public String toString(){ return s; } public static void main(String[] args){ Cleanser x=new Cleanser(); x.dilute();x.apply();x.scrub(); new print(x); } } class Detergent extends Cleanser{ public void scrub(){ append(" Detergent.scrub()"); } public void foam(){ append(" foam()"); } } class Sub extends Detergent{ public void scrub(){ append(" sub.scrub"); super.scrub(); } public void sterilize(){ append("sub.sterilize()"); } }
时间: 2024-12-25 01:07:17