精华内容
下载资源
问答
  • Java编程思想第四版 第四章个人练习

    千次阅读 2014-11-03 15:21:17
    Java编程思想第四版 第四章个人练习

    第四章

    练习1:(1)写一个程序,打印1到100的值

    public static void main(String[] args) {
    		test(100);
    	}
    	
    	public static void test(int num){
    		int i=0;
    		while(i<num){
    			System.out.print(++i);
    			if(i!=100){				
    				System.out.print("、");
    			}
    		}
    		
    		System.out.println();
    		int j=0;
    		do{
    			System.out.print(++j);
    			if(j!=100){				
    				System.out.print("、");
    			}
    		}while(j<100);
    		
    		System.out.println();
    		for(int k=0;k<100;){
    			System.out.print(++k);
    			if(k!=100){				
    				System.out.print("、");
    			}
    		}
    	}


    练习2:(2)写一个程序,产生25个int类型的随机数,对于每一个随机数,使用if-else语句来将其分类为大于、小于,或等于紧随它而随机产生的值。

    	public static void main(String[] args) {
    		test();
    	}
    	
    	public static void test(){
    		int num[] =new int[25];
    		for(int i=0;i<25;i++){
    			Random r=new Random();
    			int n=r.nextInt();
    			num[i]=n;
    			if(i>0){
    				compare(num[i-1],num[i]);
    			}
    		}
    	}
    
    	public static void compare(int n1,int n2){
    		//System.out.println(n1+"、"+n2+"\n n1>n2:"+(n1>n2)+"\t"+"n1==n2:"+(n1==n2)+"\t"+"n1<n2:"+(n1<n2));
    		if(n1>n2){
    			System.out.println(n1+"大于"+n2);
    		}else if(n1<n2){
    			System.out.println(n1+"小于"+n2);
    		}else {
    			System.out.println(n1+"等于"+n2);
    		}
    	}


    练习3:(1)修改练习2,把代码用一个while无限循环包括起来。然后运行它直至用键盘中断其运行(通常是通过按Ctrl+c).

    public static void main(String[] args) {
    		test();
    	}
    	
    	public static void test(){
    		int num[] =new int[2];
    		int i=0;
    		boolean flag=false;
    		while(true){
    			Random r=new Random();
    			int n=r.nextInt();			
    			if(flag){
    				num[i]=n;
    				compare(num[0],num[1]);
    			}else{
    				flag=true;
    				num[i]=n;
    			}
    			i=i==0?1:0;
    		}
    	}
    
    	public static void compare(int n1,int n2){
    		//System.out.println(n1+"、"+n2+"\n n1>n2:"+(n1>n2)+"\t"+"n1==n2:"+(n1==n2)+"\t"+"n1<n2:"+(n1<n2));
    		if(n1>n2){
    			System.out.println(n1+"大于"+n2);
    		}else if(n1<n2){
    			System.out.println(n1+"小于"+n2);
    		}else {
    			System.out.println(n1+"等于"+n2);
    		}
    	}


    练习4:(3)写一个程序,使用两个嵌套的for循环和取余操作符(%)来探测和打印素数(只能被其自身和1整除,而不能被其它数字整除的整数)。

           public static void main(String[] args) {
    		test(33);
    	}
    	
    	public static boolean test(int num){
    		for(int i=2;i<num;i++){
    			if(num%i==0){
    				System.out.println(num+" 不是素数");
    				return true;
    			}
    		}
    		System.out.println(num+" 是素数");
    		return false;
    	}



    练习5:(4)重复第3章中的练习10,不要用Integer.toBinaryString()方法,而是用三元操作符和按位操作符来显示二进制的1和0。


    展开全文
  • 最近开始看Java编程思想第四版中文版,一本砖头大的书,在这里记下读数笔记以后自己看看吧。今天是第一章 对象导论。

    最近开始看Java编程思想第四版中文版,一本砖头大的书,在这里记下读数笔记以后自己看看吧。今天是第一章 对象导论。


    第一章、对象导论


                 1.抽象过程


    万物皆为对象。

    程序是对象的集合,它们通过发送消息来告知彼此所要做的。

    每个对象都有自己的由其它对象构成的存储。

    每个对象都有其类型,每个对象都是某个类的一个实例(instance)。

    某一特定类型的所有对象都可以接受同样的消息。


                 2.每个对象都有一个接口


    每个对象都只能满足某些请求,这些请求是由接口(instance)所定义的,决定接口的便是类型。




    3.每个对象都提供一个服务

    将对象看做服务者可以提高对象的内聚性。高内聚是软件设计的基本质量要求之一。

    可以将一个拥有很多功能的对象拆分成多个各司其职的对象。


    4.被隐藏的具体实现

    客户端程序员的目标是收集各种用来实现快速应用开发的类。(介不就是我嘛,各种下demo拼凑代码TAT)

    为什么要进行访问控制

    1.让客户端程序员无法触及他们不该触及的部分——这些部分对于内部操作是必须的,但不是用户解决特定问题所需要的接口的一部分。减少客户端程序员需要考虑的东西,忽略不重要的东西。

    2.允许库设计者可以改变内部的工作方式而不用担心会影响到客户端程序员。


    5.复用的具体实现

    复用对象:
     
    (1) 直接使用该类的对象
    (2) 创建一个成员对象


    使用现有的类合成新的类,称为“组合”,如果组合是动态发生的,则称为“聚合”。


    在创建新类时,优先考虑组合,再考虑继承。


    6.继承

    基类和导出类产生差异:


    直接在导出类添加新方法


    覆盖(overriding)原方法


    7.伴随多态的可互换对象

    将导出类看做它的基类的过程称为向上转型


    方法可以在不知道对象的实际类型时,做出正确的行为。




    8.单根继承结构

    除了C++以外的所有OOP语言,所有类最终都继承自单一的基类。这个终极基类即Object


    单根继承所有对象都具有统一的接口,给编程带来了更大的灵活性。
    垃圾回收器的实现变得容易许多。


    C++这样,优点:额外的灵活性。 缺点:需要构建自己的继承体系,不兼容


    9.容器

    不同的容器提供了不同类型的接口和外部行为
    不同的容器对于某些操作具有不同的效率


    为了避免向下转型为错误的类型,因此有了参数化类型机制,参数画类型就是一个编译器可以自动定制用于特定类型上的类。(感觉就是泛型)



    10.对象的创建和生命周期

    对象的创建
    C++认为效率控制是最重要的议题,在堆栈或者静态存储区域创建对象。


    Java在创建对象的时候可以不用知道对象的确切数量,生命周期和类型。


    Java完全采用了动态内存分配的方式。它认为对象变得复杂后,查找和释放存储空间的开销就不那么那么重要了。提高灵活性,牺牲了时间。


    对象的生命周期
    Java提供了“垃圾回收器”机制,可以自动发现对象何时不再被使用,继而销毁它。


    垃圾回收器可以避免内存泄露的问题。


    11.异常处理:处理错误

    异常是一种对象,它从出错地点被“抛出”,并被专门设计用来处理特定类型错误的相应的异常处理器“捕获”。

    异常不能忽略,所以它保证一定会在某处得到处理。它提供了一种从错误状况进行可靠恢复的路径。

    异常处理不适面相对象的特征。



    12.并发编程

    使用线程,但是可能遇到一个隐患,就是共享资源的问题。


    某个任务锁定某项资源,完成其任务,然后释放资源锁,使其它任务可以使用这项资源。


    13.Java与Internet

    客户/服务器系统的核心思想是:系统具有一个中央信息存储池,用来存储某种数据,它通常位于数据库中,你可以根据需要将它分发给某些人员或机器集群。

    信息存储池、用于分发信息的软件以及消息与软件所驻留的机器或机群被总称为服务器。

    客户端编程:
    1.插件(plug-in)
    2.脚本语言(scripting language)'
    3.java
    4..NET和C#
    5.企业内部网Inttanet












    展开全文
  • java编程思想 第四版 第六章 答案,中文版 练习1:(1)在某个包中创建一个类,在这个类所处的包的外部创建该类的一个实例。 练习2:(1)将本节中的代码片段改写为完整的程序,并校验实际所发生的冲突。 练习3:(1...

    欢迎加群:239063848
    进群须知:本群仅用于技术分享与交流,问题发布与解答
    禁止闲聊、非诚勿扰


    练习1:(1)在某个包中创建一个类,在这个类所处的包的外部创建该类的一个实例。

    import mil.oms.main.test.Test;
     
    public   class  MainTest {  
           
        public static void main(String args[]){    	
        	Test test=new Test();
        }
        /**
         	运行结果
    		Test()实例化……
         */
    
    } 

    package mil.oms.main.test;
    
    public class Test{	
    	public Test(){
    		System.out.println("Test()实例化……");
    	}
    }

    练习2:(1)将本节中的代码片段改写为完整的程序,并校验实际所发生的冲突。

    import mil.oms.main.test.Vector;
    import java.util.*;
    
    public   class  MainTest {  
           
        public static void main(String args[]){    	
        	Vector vector=new Vector();
        	java.util.Vector vector1=new java.util.Vector();
        }
    }  
    package mil.oms.main.test;
    
    public class Vector{	
    	public Vector(){
    		System.out.println("Vector()实例化……");
    	}
    }

    练习3:(1)创建两个包:debug和debugoff,他们都包含一个相同的类,该类有一个debug()方法,第一个版本显示发送给控制台的String参数,而第二版本什么也不做,使用静态import语句将该类导入到一个测试程序中,并示范条件编译效果。 

    import debug.Test;
    
    public   class  MainTest {  
           
        public static void main(String args[]){    	
        	Test t=new Test();
        	t.debug();
        }
        /**
         * 运行结果
    		Test()……
         */
    } 
    package debug;
    
    public class Test{	
    	public void debug(){
    		System.out.println("Test()……");
    	}
    }
    package debugoff;
    
    public class Test{	
    	public void debug(){
    		
    	}
    }
    练习4:(2)展示protected方法具有包访问权限,但是它仍旧不是public的。 
    package debug;
    
    public   class  MainTest {  
           
        public static void main(String args[]){
        	Test t=new Test();
        	t.debug();
        }
    }  

    package debug;
    
    public class Test{	
    	protected void debug(){
    		System.out.println("Test()……");
    	}
    }

    练习5:(2)创建一个带有public,private,protected和包访问权限域以及方法成员的类。创建一个该类的一个对象,看看在你试图调用所有类成员时,会得到什么类型的编译信息。请注意,处于同一个目录中的所有类都是默认包的一部分

    package debug;
    
    public   class  MainTest {  
           
        public static void main(String args[]){
        	Test t=new Test();
        	//System.out.println(t.str1);
        	System.out.println(t.str2);
        	System.out.println(t.str3);
        	//t.debug1();
        	t.debug2();
        	t.debug3();
        	/**
        	 * 输出
    			value2
    			value3
    			debug2()……
    			debug3()……
        	 */
        }
    }  

    package debug;
    
    public class Test{
    	
    	private String str1="value1";
    	
    	protected String str2="value2";
    	
    	public String str3="value3";
    	
    	private void debug1(){
    		System.out.println("debug1()……");
    	}
    	protected void debug2(){
    		System.out.println("debug2()……");
    	}
    	public void debug3(){
    		System.out.println("debug3()……");
    	}
    }
    


    练习6:(1)创建一个带有protected数据的类,运用在第一个类中处理protected数据的方法在相同的文件中创建第二个类。

    package debug;
    
    public   class  MainTest {  
           
        public static void main(String args[]){
        	Test t=new Test();
        	System.out.println(t.str2);
        	/**
        	 * 输出
    			value2
        	 */
        }
    }  

    package debug;
    
    public class Test{
    	protected String str2="value2";
    }
    

    练习7:根据描述access和Widget的代码片段创建类库,在某个不属于access类库的类中创建一个Widget实例  

    package access.local;  
    import access.debug.Widget;;  
    public class Test {  
        public static void main(String args[]){  
            new Widget();  
        }  
    }

    package access.debug;  
      
    public class Widget {  
        public Widget(){  
            System.out.println("Widget!");  
        }  
    }  


    练习8:效仿实例Lunch.java的形式,创建一个名为ConnectionManager的类,该类管理一个元素为Connection对象的固定数组。客户端程序员不能直接创建Connection对象,而只能通过ConnectionManager中的某个static方法来获取他们。当ConnectionManager之中不再有对象时,它会返回null引用。在main()之中检测这些类。 

    package test;
    
    import java.util.Arrays;
    
    
    public class ConnectionManager {
    	
    	public static  Connection [] cons=new Connection[5];
    	
    	static {
    		System.out.println("----------初始化Connection对象----");
    		for(int i=0;i<5;i++){
    			cons[i]=Connection.makeConnection();
    		}
    	}
    	
    	public static  Connection getConnection(){
    		int l=cons.length;
    		if(l>0){
    			Connection con=cons[--l];
    			cons=Arrays.copyOf(cons, l);
    			return con;
    		}else{
    			return null;
    		}
    	}
    
    	public static void main(String args[]){
    		try {
    			for(int i=0;i<7;i++){	
    				Connection con=ConnectionManager.getConnection();
    				System.out.println(i+"、"+con);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	/**
    	 * 打印结果:
    ----------初始化Connection对象----
    0、test.Connection@527c6768
    1、test.Connection@527c6768
    2、test.Connection@527c6768
    3、test.Connection@527c6768
    4、test.Connection@527c6768
    5、null
    6、null
    	 */
    	
    
    }
    class Connection{
    	
    	private static Connection connection=new Connection();
    	
    	private Connection(){
    		
    	}
    	
    	public static Connection makeConnection(){
    		return connection;
    	}
    }
    

    练习9:(2)在access/local目录下编写以下文件(假定access/local目录在你的CLASSPATH中):

    package test.access.foreign;
    
    public class Foreign {
    	
    	public static void main(String args[]){
    		PackagedClass PackagedClass=new PackagedClass();//由于此类只有包访问权限,编译未通过
    	}
    	/**
    	 * 打印结果:
    	 */
    }

    package test.access.local;
    
    public class Foreign {
    	public static void main(String args[]){
    		PackagedClass PackagedClass=new PackagedClass();//在同一个包中,可正确引用
    	}
    	/**
    	 * 打印结果:
    	 */
    }
    class PackagedClass{
    	
    	public PackagedClass(){
    		
    	}
    }
    



    展开全文
  • Java编程思想第四版第十四章习题

    千次阅读 2019-08-08 21:59:14
    1In ToyTest.java, comment out Toy's default constructor andexplain what happens. package job; import java.util.*; interface HasBatteries {} interface Waterproof {} interface Shoots {} class .....

    1 In ToyTest.java, comment out Toy's default constructor and explain what happens.

    package job;
    import java.util.*;
    
    interface HasBatteries {}
    
    interface Waterproof {}
    
    interface Shoots {}
    
    
    
    class Toy {
    
        //Toy() {}
    
        Toy(int i) {}
    
    }
    
    
    
    class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots {
    
        FancyToy() {
            super(1);
        }
    
    }
    
    
    
    public class Main {
    
        static void printInfo(Class cc) {
    
            System.out.println("Class name: " + cc.getName() +
    
                    " is interface? [" + cc.isInterface() + "]");
    
            System.out.println("Simple name: " + cc.getSimpleName());
    
            System.out.println("Canonical name : " + cc.getCanonicalName());
    
        }
    
        public static void main(String[] args) {
    
            Class c = null;
    
            try {
    
                c = Class.forName("job.FancyToy");
    
            } catch (ClassNotFoundException e) {
    
                System.out.println("Can't find FancyToy");
    
                System.exit(1);
    
            }
    
            printInfo(c);
    
            for (Class face : c.getInterfaces())
    
                printInfo(face);
    
            Class up = c.getSuperclass();
    
            Object obj = null;
    
            try {
    
                // Requires default constructor:
    
                obj = up.newInstance();
    
            } catch (InstantiationException e) {
    
                System.out.println("Cannot instantiate");
    
                System.exit(1);
    
            } catch (IllegalAccessException e) {
    
                System.out.println("Cannot access");
    
                System.exit(1);
    
            }
    
            printInfo(obj.getClass());
    
        }
    
    }
    

    output:

     Class name: job.FancyToy is interface? [false]
    Simple name: FancyToy
    Canonical name : job.FancyToy
    Class name: job.HasBatteries is interface? [true]
    Simple name: HasBatteries
    Canonical name : job.HasBatteries
    Class name: job.Waterproof is interface? [true]
    Simple name: Waterproof
    Canonical name : job.Waterproof
    Class name: job.Shoots is interface? [true]
    Simple name: Shoots
    Canonical name : job.Shoots
    Cannot instantiate

     

    2 Incorporate a new kind of interface into ToyTest.java andverify that it is detected and displayed properly.

    package job;
    import java.util.*;
    
    interface HasBatteries {}
    
    interface Waterproof {}
    
    interface Shoots {}
    
    interface A{}
    
    
    
    class Toy {
    
        Toy() {}
    
        Toy(int i) {}
    
    }
    
    
    
    class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots,A {
    
        FancyToy() {
            super(1);
        }
    
    }
    
    
    
    public class Main {
    
        static void printInfo(Class cc) {
    
            System.out.println("Class name: " + cc.getName() +
    
                    " is interface? [" + cc.isInterface() + "]");
    
            System.out.println("Simple name: " + cc.getSimpleName());
    
            System.out.println("Canonical name : " + cc.getCanonicalName());
    
        }
    
        public static void main(String[] args) {
    
            Class c = null;
    
            try {
    
                c = Class.forName("job.FancyToy");
    
            } catch (ClassNotFoundException e) {
    
                System.out.println("Can't find FancyToy");
    
                System.exit(1);
    
            }
    
            printInfo(c);
    
            for (Class face : c.getInterfaces())
    
                printInfo(face);
    
            Class up = c.getSuperclass();
    
            Object obj = null;
    
            try {
    
                // Requires default constructor:
    
                obj = up.newInstance();
    
            } catch (InstantiationException e) {
    
                System.out.println("Cannot instantiate");
    
                System.exit(1);
    
            } catch (IllegalAccessException e) {
    
                System.out.println("Cannot access");
    
                System.exit(1);
    
            }
    
            printInfo(obj.getClass());
    
        }
    
    }
    

    output:

    Class name: job.FancyToy is interface? [false]
    Simple name: FancyToy
    Canonical name : job.FancyToy
    Class name: job.HasBatteries is interface? [true]
    Simple name: HasBatteries
    Canonical name : job.HasBatteries
    Class name: job.Waterproof is interface? [true]
    Simple name: Waterproof
    Canonical name : job.Waterproof
    Class name: job.Shoots is interface? [true]
    Simple name: Shoots
    Canonical name : job.Shoots
    Class name: job.A is interface? [true]
    Simple name: A
    Canonical name : job.A
    Class name: job.Toy is interface? [false]
    Simple name: Toy
    Canonical name : job.Toy
     

    3 Add Rhomboid to Shapes.java. Create a Rhomboid, upcast it to a Shape, then downcast it back to a Rhomboid. Try downcasting to a Circle and see what happens.

    package job;
    import java.util.*;
    abstract class Shape{
        abstract void draw();
        abstract void erase();
    }
    class Rhomboid extends Shape{
    
        public void draw() { System.out.println("Rhomboid.draw()"); }
    
        public void erase() { System.out.println("Rhomboid.erase()"); }
    
    }
    
    class Circle extends Shape{
    
        public void draw() { System.out.println("Circle.draw()"); }
    
        public void erase() { System.out.println("Circle.erase()"); }
    
    }
    public class Main {
    
    
        public static void main(String[] args) {
            try {
                Shape a = new Rhomboid();
    
                a.draw();
    
                ((Rhomboid) a).draw();
    
                ((Circle) a).draw();
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    
    }
    

    output:

    Rhomboid.draw()
    Rhomboid.draw()
    java.lang.ClassCastException: class job.Rhomboid cannot be cast to class job.Circle (job.Rhomboid and job.Circle are in unnamed module of loader 'app')
        at job.Main.main(Main.java:33)

     

    4 Modify the previous exercise so that it uses instancof to check the type before performing the downcast.

    package job;
    import java.util.*;
    abstract class Shape{
        abstract void draw();
        abstract void erase();
    }
    class Rhomboid extends Shape{
    
        public void draw() { System.out.println("Rhomboid.draw()"); }
    
        public void erase() { System.out.println("Rhomboid.erase()"); }
    
    }
    
    class Circle extends Shape{
    
        public void draw() { System.out.println("Circle.draw()"); }
    
        public void erase() { System.out.println("Circle.erase()"); }
    
    }
    public class Main {
    
    
        public static void main(String[] args) {
            try {
                Shape a = new Rhomboid();
                if(a instanceof Shape) {
                    a.draw();
                }
                if(a instanceof Rhomboid) {
                    ((Rhomboid) a).draw();
                }
                else if(a instanceof Circle) {
                    ((Circle) a).draw();
                }
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    
    }
    

     

    5 Implement a rotate(Shape) method in Shapes.java, such that it checks to see if it is rotating a Circle (and, if so, doesn't perform the operation).

    package job;
    import java.util.*;
    class Shape {
    
        public void draw() {
        }
    
        public void erase() {
        }
    
        public void rotate() {
        }
    
    }
    
    class Square extends Shape {
    
        public void draw() {
            System.out.println("Square.draw()");
        }
    
        public void erase() {
            System.out.println("Square.erase()");
        }
    
        public void rotate() {
            System.out.println("Square.rotate()");
        }
    
    }
    
    class Triangle extends Shape {
    
        public void draw() {
            System.out.println("Triangle.draw()");
        }
    
        public void erase() {
            System.out.println("Triangle.erase()");
        }
    
        public void rotate() {
            System.out.println("Triangle.rotate()");
        }
    
    }
    
    class Circle extends Shape {
    
        public void draw() {
            System.out.println("Circle.draw()");
        }
    
        public void erase() {
            System.out.println("Circle.erase()");
        }
    
        public void rotate() {
            System.out.println("Circle.rotate()");
        }
    
    }
    
    
    
    class RandomShapeGenerator {
    
        private Random rand = new Random(47);
    
        public RandomShapeGenerator() {
        }
    
        public Shape next() {
    
            switch (rand.nextInt(3)) {
    
                default:
    
                case 0:
                    return new Circle();
    
                case 1:
                    return new Square();
    
                case 2:
                    return new Triangle();
    
            }
    
        }
    
    }
    
    
    
    public class Main {
    
        private static RandomShapeGenerator gen = new RandomShapeGenerator();
    
        public static void main(String[] args) {
    
            Shape[] s = new Shape[9];
    
            // Fill up the array with shapes:
    
            for (int i = 0; i < s.length; i++)
    
                s[i] = gen.next();
    
            // Make polymorphic method calls:
    
            for (Shape shp : s) {
    
                if (!(shp instanceof Circle)) shp.rotate();
    
            }
    
        }
    }
    

     output:

    Radom

    6 Modify Shapes.java so that it can "highlight" (set a flag in) all shapes of a particular type.  The toString() method for each derived Shape should indicate whether that Shape is "highlighted."

    package job;
    import java.util.*;
    class Shape {
        boolean flag=false;
    
        public void draw() {
        }
    
        public void erase() {
        }
    
        public void rotate() {
        }
    
        void flag() {
        }
    }
    
    class Square extends Shape {
    
        public void draw() {
            System.out.println("Square.draw()");
        }
    
        public void erase() {
            System.out.println("Square.erase()");
        }
    
        public void rotate() {
            System.out.println("Square.rotate()");
        }
    
        void flag() {
            flag = true;
        }
    
        public String toString() {
            return ("Square: " + flag);
        }
    }
    
    class Triangle extends Shape {
    
        public void draw() {
            System.out.println("Triangle.draw()");
        }
    
        public void erase() {
            System.out.println("Triangle.erase()");
        }
    
        public void rotate() {
            System.out.println("Triangle.rotate()");
        }
    
        void flag() {
            flag = true;
        }
    
        public String toString() {
            return ("Triangle: " + flag);
        }
    }
    
    class Circle extends Shape {
    
        public void draw() {
            System.out.println("Circle.draw()");
        }
    
        public void erase() {
            System.out.println("Circle.erase()");
        }
    
        public void rotate() {
            System.out.println("Circle.rotate()");
        }
    
        void flag() {
            flag = true;
        }
    
        public String toString() {
            return ("Circle: " + flag);
        }
    }
    
    
    
    class RandomShapeGenerator {
    
        private Random rand = new Random(47);
    
        public RandomShapeGenerator() {
        }
    
        public Shape next() {
    
            switch (rand.nextInt(3)) {
    
                default:
    
                case 0:
                    return new Circle();
    
                case 1:
                    return new Square();
    
                case 2:
                    return new Triangle();
    
            }
    
        }
    
    }
    
    
    
    public class Main {
    
        private static RandomShapeGenerator gen = new RandomShapeGenerator();
    
        public static void main(String[] args) {
    
            Shape[] s = new Shape[9];
    
            // Fill up the array with shapes:
    
            for (int i = 0; i < s.length; i++)
    
                s[i] = gen.next();
    
            // Make polymorphic method calls:
    
            for (Shape a : s) {
    
                if (!(a instanceof Circle)) {
                    a.rotate();
                    a.flag();
                    System.out.println(a);
                }
            }
    
        }
    }
    

    output:

    Radom 

    7 Modify SweetShop.java so that each type of object creation is controlled by a command-line argument. That is, if your command line is "java  SweetShop Candy," then only the Candy object is created. Notice how you  can control which Class object are loaded via the command-line argument.

    package job;
    import java.util.*;
    class Candy {
        static {
            System.out.println("Loading Candy");
        }
    }
    class Gum {
        static {
            System.out.println("Loading Gum");
        }
    }
    
    class Cookie {
        static {
            System.out.println("Loading Cookie");
        }
    }
    
    
    class Main{
        public static void main(String[] args){
            Other.main(new String[]{"job.Candy"});
        }
    }
    
    class Other {
    
    
        public static void main(String[] args) {
            if (args.length < 1) {
                System.out.println("args is null");
                System.exit(0);
            }
            Class c = null;
            try {
                c = Class.forName(args[0]);
                System.out.println(c.getName() + " " + c.isInterface());
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    }
    

    output:

    Loading Candy
    job.Candy false 

    8 Write a method that takes an object and recursively prints allthe classes in that object's hierarchy.

     

    package job;
    import java.util.*;
    class A{
    
    }
    class B extends A{
    
    }
    class C extends B{
    
    }
    public class Main{
        static void Aa(Class obj){
            System.out.println(obj.getName());
            try{
                Aa(obj.getSuperclass());
            }catch (Exception e){}
        }
        public static void main(String[] args){
            Class c=null;
            try{
                c=Class.forName("job.C");
                Aa(c);
            }catch (Exception e){
                e.printStackTrace(System.out);
            }
        }
    }
    
    

    output:

    job.C
    job.B
    job.A
    java.lang.Object 

    9 Modify the previous exercise so that it uses Class.getDeclaredFields()to also display information about the fields in a class.

     

    package job;
    import java.util.*;
    class A{
    
    }
    class B extends A{
    
    }
    class C extends B{
    
    }
    public class Main{
        static void Aa(Class obj){
            System.out.println(obj.getName());
            try{
                Aa(obj.getSuperclass());
            }catch (Exception e){}
        }
        public static void main(String[] args){
            Class c=null;
            try{
                c=Class.forName("job.C");
                System.out.println(c.getDeclaredFields());
                Aa(c);
            }catch (Exception e){
                e.printStackTrace(System.out);
            }
        }
    }
    
    

    output:

    [Ljava.lang.reflect.Field;@34ce8af7
    job.C
    job.B
    job.A
    java.lang.Object 

    10 Write a program to determine whether an array of char is a primitive type or a true Object.

    package job;
    import java.util.*;
    
    public class Main{
        static void Aa(Class obj){
            System.out.println(obj.getName());
            try{
                Aa(obj.getSuperclass());
            }catch (Exception e){}
        }
        public static void main(String[] args){
            char[] a=new char[5];
            try{
                Class c=a.getClass();
                Aa(c);
            }catch (Exception e){
                e.printStackTrace(System.out);
            }
        }
    }
    
    

    output:

    [C
    java.lang.Object

    故:对象

    11 你在难为我胖虎?

    12 Use TypeCounter with the CoffeeGenerator.java class in the Generics chapter.

    
    import java.util.*;
    
    import generics.coffee.*;
    
     
    
    class TypeCounter extends HashMap<Class<?>,Integer>{
    
      private Class<?> baseType;
    
      public TypeCounter(Class<?> baseType) {
    
        this.baseType = baseType;
    
      }
    
      public void count(Object obj) {
    
        Class<?> type = obj.getClass();
    
        if(!baseType.isAssignableFrom(type))
    
          throw new RuntimeException(obj + " incorrect type: "
    
            + type + ", should be type or subtype of "
    
            + baseType);
    
        countClass(type);
    
      }	
    
      private void countClass(Class<?> type) {
    
        Integer quantity = get(type);
    
        put(type, quantity == null ? 1 : quantity + 1);
    
        Class<?> superClass = type.getSuperclass();
    
        if(superClass != null &&
    
           baseType.isAssignableFrom(superClass))
    
          countClass(superClass);
    
      }
    
      public String toString() {
    
        StringBuilder result = new StringBuilder("{");
    
        for(Map.Entry<Class<?>,Integer> pair : entrySet()) {
    
          result.append(pair.getKey().getSimpleName());
    
          result.append("=");
    
          result.append(pair.getValue());
    
          result.append(", ");
    
        }
    
        result.delete(result.length()-2, result.length());
    
        result.append("}");
    
        return result.toString();
    
      }
    
    }
    
    public class Main{
    
        public static void main(String[] args){
    
           TypeCounter tc=new TypeCounter(Coffee.class);
    
            for(Coffee c : new CoffeeGenerator(5)){
    
                tc.count(c);
    
            }
    
            System.out.println(tc);
    
        }
    
    }
    

     

    13 Use TypeCounter with the RegisteredFactories.java class in this chapter.

    
    
    import typeinfo.factory.*;
    
    import java.util.*;
    
     
    
    class Part {
    
      public String toString() {
    
        return getClass().getSimpleName();
    
      }
    
      static List<Factory<? extends Part>> partFactories =
    
        new ArrayList<Factory<? extends Part>>();	
    
      static {
    
        // Collections.addAll() gives an "unchecked generic
    
        // array creation ... for varargs parameter" warning.
    
        partFactories.add(new FuelFilter.Factory());
    
        partFactories.add(new AirFilter.Factory());
    
        partFactories.add(new CabinAirFilter.Factory());
    
        partFactories.add(new OilFilter.Factory());
    
        partFactories.add(new FanBelt.Factory());
    
        partFactories.add(new PowerSteeringBelt.Factory());
    
        partFactories.add(new GeneratorBelt.Factory());
    
      }
    
      private static Random rand = new Random(47);
    
      public static Part createRandom() {
    
        int n = rand.nextInt(partFactories.size());
    
        return partFactories.get(n).create();
    
      }
    
    }	
    
     
    
    class Filter extends Part {}
    
     
    
    class FuelFilter extends Filter {
    
      // Create a Class Factory for each specific type:
    
      public static class Factory
    
      implements typeinfo.factory.Factory<FuelFilter> {
    
        public FuelFilter create() { return new FuelFilter(); }
    
      }
    
    }
    
     
    
    class AirFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<AirFilter> {
    
        public AirFilter create() { return new AirFilter(); }
    
      }
    
    }	
    
     
    
    class CabinAirFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<CabinAirFilter> {
    
        public CabinAirFilter create() {
    
          return new CabinAirFilter();
    
        }
    
      }
    
    }
    
     
    
    class OilFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<OilFilter> {
    
        public OilFilter create() { return new OilFilter(); }
    
      }
    
    }	
    
     
    
    class Belt extends Part {}
    
     
    
    class FanBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<FanBelt> {
    
        public FanBelt create() { return new FanBelt(); }
    
      }
    
    }
    
     
    
    class GeneratorBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<GeneratorBelt> {
    
        public GeneratorBelt create() {
    
          return new GeneratorBelt();
    
        }
    
      }
    
    }	
    
     
    
    class PowerSteeringBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<PowerSteeringBelt> {
    
        public PowerSteeringBelt create() {
    
          return new PowerSteeringBelt();
    
        }
    
      }
    
    }	
    
    class TypeCounter extends HashMap<Class<?>,Integer>{
    
      private Class<?> baseType;
    
      public TypeCounter(Class<?> baseType) {
    
        this.baseType = baseType;
    
      }
    
      public void count(Object obj) {
    
        Class<?> type = obj.getClass();
    
        if(!baseType.isAssignableFrom(type))
    
          throw new RuntimeException(obj + " incorrect type: "
    
            + type + ", should be type or subtype of "
    
            + baseType);
    
        countClass(type);
    
      }	
    
      private void countClass(Class<?> type) {
    
        Integer quantity = get(type);
    
        put(type, quantity == null ? 1 : quantity + 1);
    
        Class<?> superClass = type.getSuperclass();
    
        if(superClass != null &&
    
           baseType.isAssignableFrom(superClass))
    
          countClass(superClass);
    
      }
    
      public String toString() {
    
        StringBuilder result = new StringBuilder("{");
    
        for(Map.Entry<Class<?>,Integer> pair : entrySet()) {
    
          result.append(pair.getKey().getSimpleName());
    
          result.append("=");
    
          result.append(pair.getValue());
    
          result.append(", ");
    
        }
    
        result.delete(result.length()-2, result.length());
    
        result.append("}");
    
        return result.toString();
    
      }
    
    }
    
    public class Main{
    
        public static void main(String[] args){
    
           TypeCounter tc=new TypeCounter(Part.class);
    
            for(int i = 0; i < 10; i++)
    
                tc.count(Part.createRandom());
    
            System.out.println(tc);
    
        }
    
    }
    
     
    

     

    14 A constructor is a kind of factory method. Modify RegisteredFactories.java so that instead of using explicit factories, the class object is stored in the List, and newInstance() is used to create each object.

    package job;
    import java.util.*;
    interface Factory<T>{
        T create();
    }
    
    class Part {
    
        public String toString() {
    
            return getClass().getSimpleName();
    
        }
    
        static List<Class<? extends Part>> partClasses =
    
                new ArrayList<Class<? extends Part>>();
    
        static {
    
            // Collections.addAll() gives an "unchecked generic
    
            // array creation ... for varargs parameter" warning.
    
            partClasses.add(FuelFilter.class);
    
            partClasses.add(AirFilter.class);
    
            partClasses.add(CabinAirFilter.class);
    
            partClasses.add(OilFilter.class);
    
            partClasses.add(FanBelt.class);
    
            partClasses.add(PowerSteeringBelt.class);
    
            partClasses.add(GeneratorBelt.class);
    
        }
    
        private static Random rand = new Random(47);
    
        public static Part createRandom() {
    
            int n = rand.nextInt(partClasses.size());
    
            try{return partClasses.get(n).newInstance();
    
            }catch(InstantiationException e){
    
                throw new RuntimeException(e);
    
            }catch(IllegalAccessException e){
    
                throw new RuntimeException(e);
    
            }
    
        }
    
    }
    
    
    
    class Filter extends Part {}
    
    
    
    class FuelFilter extends Filter {
    
        // Create a Class Factory for each specific type:
    
        public static class Factory
    
                implements typeinfo.factory.Factory<FuelFilter> {
    
            public FuelFilter create() { return new FuelFilter(); }
    
        }
    
    }
    
    
    
    class AirFilter extends Filter {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<AirFilter> {
    
            public AirFilter create() { return new AirFilter(); }
    
        }
    
    }
    
    
    
    class CabinAirFilter extends Filter {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<CabinAirFilter> {
    
            public CabinAirFilter create() {
    
                return new CabinAirFilter();
    
            }
    
        }
    
    }
    
    
    
    class OilFilter extends Filter {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<OilFilter> {
    
            public OilFilter create() { return new OilFilter(); }
    
        }
    
    }
    
    
    
    class Belt extends Part {}
    
    
    
    class FanBelt extends Belt {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<FanBelt> {
    
            public FanBelt create() { return new FanBelt(); }
    
        }
    
    }
    
    
    
    class GeneratorBelt extends Belt {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<GeneratorBelt> {
    
            public GeneratorBelt create() {
    
                return new GeneratorBelt();
    
            }
    
        }
    
    }
    
    
    
    class PowerSteeringBelt extends Belt {
    
        public static class Factory
    
                implements typeinfo.factory.Factory<PowerSteeringBelt> {
    
            public PowerSteeringBelt create() {
    
                return new PowerSteeringBelt();
    
            }
    
        }
    
    }
    
    
    
    public class Main {
    
        public static void main(String[] args) {
    
            for(int i = 0; i < 10; i++)
    
                System.out.println(Part.createRandom());
    
        }
    
    }
    
    
    
    
    
    

    15 Implement a new PetCreator using Registered Factories, and modify the Pets Facade so that it uses this one instead of the other two. Ensure that the rest of the examples that use Pets.java still work correctly.

    package job;
    import typeinfo.pets.*;
    
    import typeinfo.factory.*;
    import java.util.*;
    
    public class PetFactory{
    
        static List<Factory<? extends Pet>> petFactories=new ArrayList<Factory<? extends Pet>>();
    
        static{
    
            //System.out.println(new Rodent.Factory());
    
            petFactories.add(new Pet.Factory());
    
            petFactories.add(new Cat.Factory());
    
            petFactories.add(new Cymric.Factory());
    
            petFactories.add(new Dog.Factory());
    
            petFactories.add(new EgyptianMau.Factory());
    
            //petFactories.add(new Gerbil.Factory());
    
            //petFactories.add(new Hamster.Factory());
    
            petFactories.add(new Manx.Factory());
    
            //petFactories.add(new Mouse.Factory());
    
            petFactories.add(new Mutt.Factory());
    
            petFactories.add(new Pug.Factory());
    
            //petFactories.add(new Rat.Factory());
    
            //petFactories.add(new Rodent.Factory());//!无法找到??
    
        }
    
        private static Random rand=new Random(55);
    
        public static Pet createRandom(){
    
            return petFactories.get(rand.nextInt(petFactories.size())).create();
    
        }
    
        public static void main(String[] args){
    
            for(int i=0;i<10;i++)
    
                System.out.println(PetFactory.createRandom());
    
        }
    
    }
    
    
    
    import typeinfo.pets.*;
    
            import java.util.*;
    
    
    
    public class Pets {
    
        public static final PetCreator creator =
    
                new LiteralPetCreator();
    
        public static Pet randomPet() {
    
            return PetFactory.createRandom()/*.randomPet()*/;
    
        }
    
        public static Pet[] createArray(int size) {
    
            return creator.createArray(size);
    
        }
    
        public static ArrayList<Pet> arrayList(int size) {
    
            return creator.arrayList(size);
    
        }
    
        public static void main(String[] args){
    
            for(int i=0;i<10;i++)
    
                System.out.println(Pets.randomPet());
    
        }
    
    }
    

    16 Modify the Coffee hierarchy in the Generics chapter to use Registered Factories.

    package job;
    import typeinfo.factory.*;
    
    import generics.coffee.*;
    
    import java.util.*;
    
    public class Ja14_16 implements Generator<Coffee>, Iterable<Coffee>{
    
        private static List<Factory<? extends Coffee>> coFactory=new ArrayList<Factory<? extends Coffee>>();
    
        static{
    
            coFactory.add(new Coffee.Factory());
    
            coFactory.add(new Americano.Factory());
    
            coFactory.add(new Breve.Factory());
    
            coFactory.add(new Cappuccino.Factory());
    
            coFactory.add(new Latte.Factory());
    
            coFactory.add(new Mocha.Factory());
    
        }
    
        private static Random rand = new Random(66);
    
        public Ja14_16() {}
    
        private int size = 0;
    
        public Ja14_16(int sz) { size = sz; }
    
        public Coffee next() {
    
            try {
    
                return (Coffee)
    
                        coFactory.get(rand.nextInt(coFactory.size())).create();
    
                // Report programmer errors at run time:
    
            } catch(Exception e) {
    
                throw new RuntimeException(e);
    
            }
    
        }
    
        class CoffeeIterator implements Iterator<Coffee> {
    
            int count = size;
    
            public boolean hasNext() { return count > 0; }
    
            public Coffee next() {
    
                count--;
    
                return Ja14_16.this.next();
    
            }
    
            public void remove() { // Not implemented
    
                throw new UnsupportedOperationException();
    
            }
    
        };
    
        public Iterator<Coffee> iterator() {
    
            return new CoffeeIterator();
    
        }
    
        public static void main(String[] args) {
    
            Ja14_16 gen = new Ja14_16();
    
            for(int i = 0; i < 5; i++)
    
                System.out.println(gen.next());
    
            for(Coffee c : new Ja14_16(5))
    
                System.out.println(c);
    
        }
    
    
    
    }
    
     
    

    17 Modify the regular expression in ShowMethods.java to additionally strip off the keywords native and final (hint: us the OR operator '|').

    
    import java.lang.reflect.*;
    
    import java.util.regex.*;
    
    import static net.mindview.util.Print.*;
    
     
    
    public class Ja14_17 {
    
      private static String usage =
    
        "usage:\n" +
    
        "ShowMethods qualified.class.name\n" +
    
        "To show all methods in class or:\n" +
    
        "ShowMethods qualified.class.name word\n" +
    
        "To search for methods involving 'word'";
    
      private static Pattern p = Pattern.compile("(\\w+\\.)|(final)|(native)");
    
      public static void main(String[] args) {
    
        if(args.length < 1) {
    
          print(usage);
    
          System.exit(0);
    
        }
    
        int lines = 0;
    
        try {
    
          Class<?> c = Class.forName(args[0]);
    
          Method[] methods = c.getMethods();
    
          Constructor[] ctors = c.getConstructors();
    
          if(args.length == 1) {
    
            for(Method method : methods)
    
              print(
    
                p.matcher(method.toString()).replaceAll(""));
    
            for(Constructor ctor : ctors)
    
              print(p.matcher(ctor.toString()).replaceAll(""));
    
            lines = methods.length + ctors.length;
    
          } else {
    
            for(Method method : methods)
    
              if(method.toString().indexOf(args[1]) != -1) {
    
                print(
    
                  p.matcher(method.toString()).replaceAll(""));
    
                lines++;
    
              }
    
            for(Constructor ctor : ctors)
    
              if(ctor.toString().indexOf(args[1]) != -1) {
    
                print(p.matcher(
    
                  ctor.toString()).replaceAll(""));
    
                lines++;
    
              }
    
          }
    
        } catch(ClassNotFoundException e) {
    
          print("No such class: " + e);
    
        }
    
      }
    
    } 
    

    18 Make ShowMethods a non-public class and verify that the synthesized default constructor no longer shows up in the output.

    
    import java.lang.reflect.*;
    
    import java.util.regex.*;
    
    import static net.mindview.util.Print.*;
    
     
    
    class Ja14_18 {
    
      private static String usage =
    
        "usage:\n" +
    
        "ShowMethods qualified.class.name\n" +
    
        "To show all methods in class or:\n" +
    
        "ShowMethods qualified.class.name word\n" +
    
        "To search for methods involving 'word'";
    
      private static Pattern p = Pattern.compile("\\w+\\.");
    
      public static void main(String[] args) {
    
        if(args.length < 1) {
    
          print(usage);
    
          System.exit(0);
    
        }
    
        int lines = 0;
    
        try {
    
          Class<?> c = Class.forName(args[0]);
    
          Method[] methods = c.getMethods();
    
          Constructor[] ctors = c.getConstructors();
    
          if(args.length == 1) {
    
            for(Method method : methods)
    
              print(
    
                p.matcher(method.toString()).replaceAll(""));
    
            for(Constructor ctor : ctors)
    
              print(p.matcher(ctor.toString()).replaceAll(""));
    
            lines = methods.length + ctors.length;
    
          } else {
    
            for(Method method : methods)
    
              if(method.toString().indexOf(args[1]) != -1) {
    
                print(
    
                  p.matcher(method.toString()).replaceAll(""));
    
                lines++;
    
              }
    
            for(Constructor ctor : ctors)
    
              if(ctor.toString().indexOf(args[1]) != -1) {
    
                print(p.matcher(
    
                  ctor.toString()).replaceAll(""));
    
                lines++;
    
              }
    
          }
    
        } catch(ClassNotFoundException e) {
    
          print("No such class: " + e);
    
        }
    
      }
    
    } 
    

    19 In ToyTest.java, use reflection to create a Toy object using the non-default constructor.

    import typeinfo.toys.*;
    
    import static net.mindview.util.Print.*;
    
    import java.lang.reflect.*;
    
     
    
    interface HasBatteries {}
    
    interface Waterproof {}
    
    interface Shoots {}
    
     
    
    class Toy {
    
      // Comment out the following default constructor
    
      // to see NoSuchMethodError from (*1*)
    
      Toy() {}
    
      Toy(int i) {print("sda");}
    
      public String toString(){
    
        return "it's Toy";
    
      }
    
    }
    
     
    
    class FancyToy extends Toy
    
    implements HasBatteries, Waterproof, Shoots {
    
      FancyToy() { super(1); }
    
    }
    
     
    
    public class Ja14_19 {
    
      static void printInfo(Class cc) {
    
        print("Class name: " + cc.getName() +
    
          " is interface? [" + cc.isInterface() + "]");
    
        print("Simple name: " + cc.getSimpleName());
    
        print("Canonical name : " + cc.getCanonicalName());
    
      }
    
      public static void main(String[] args) {
    
        /*Class c = null;
    
        try {
    
          c = Class.forName("typeinfo.toys.FancyToy");
    
        } catch(ClassNotFoundException e) {
    
          print("Can't find FancyToy");
    
          System.exit(1);
    
        }
    
    
    
        printInfo(c);	
    
        for(Class face : c.getInterfaces())
    
          printInfo(face);
    
        Class up = c.getSuperclass();
    
        Object obj = null;
    
        try {
    
          // Requires default constructor:
    
          obj = up.newInstance();
    
        } catch(InstantiationException e) {
    
          print("Cannot instantiate");
    
          System.exit(1);
    
        } catch(IllegalAccessException e) {
    
          print("Cannot access");
    
          System.exit(1);
    
        }
    
        printInfo(obj.getClass());*/
    
        try{
    
            print(Toy.class.getDeclaredConstructor(int.class).newInstance(1));
    
        }catch(Exception e){
    
            throw new RuntimeException(e);    
    
        }
    
        }
    
    } 
    

    20 Look up the interface for java.lang.Class in the JDK decumentation from http://java.sun.com. Write a program that takes the name of a class as a command line argument, then uses the Class methods to dump all the information available for that class. Test your prgram with a standard* library class and a class you create.

    import static net.mindview.util.Print.*;
    
    import java.lang.reflect.*;
    
    import java.lang.annotation.*;
    
    public class Ja14_20{
    
        public static void main(String[] args){
    
            if(args.length<1)System.exit(0);
    
            Class<?> c=null;
    
            try{
    
                c=Class.forName(args[0]);
    
            }catch(Exception e){
    
                throw new RuntimeException(e);
    
            }
    
            for(Annotation a:c.getAnnotations())print(a);
    
            for(Constructor a:c.getConstructors())print(a);
    
            for(Field a:c.getFields())print(a);
    
            //for(Method a:c.getMethods())print(a);
    
            for(Class a:c.getClasses())print(a);
    
            for(Annotation a : c.getDeclaredAnnotations())
    
    			print(a);
    
            for(Method m : c.getDeclaredMethods())
    
    			print(m);
    
            for(Type t : c.getGenericInterfaces())
    
    			print(t);
    
    		print("c.isInterface(): " + c.isInterface());
    
            
    
    		print("c.getTypeParameters(): " + c.getTypeParameters());
    
            		print("c.isAnnotation(): " + c.isAnnotation());
    
    		print("c.isAnnotationPresent(Documented.class): " + c.isAnnotationPresent(Documented.class));
    
    		print("c.isAnonymousClass(): " + c.isAnonymousClass());
    
    		print("c.isArray(): " + c.isArray());
    
    		print("c.isAssignableFrom(Object.class): " + c.isAssignableFrom(Object.class));
    
    		print("c.isEnum(): " + c.isEnum());
    
    		print("c.isInstance(Object.class): " + c.isInstance(Object.class));
    
    		print("c.isInterface(): " + c.isInterface());
    
    		print("c.isLocalClass(): " + c.isLocalClass());
    
    		print("c.isMemberClass(): " + c.isMemberClass());
    
    		print("c.isPrimitive(): " + c.isPrimitive());
    
    		print("c.isSynthetic(): " + c.isSynthetic());		
    
            
    
        }
    
    }
    

    21 Modify SimpleProxyDemo.java so that it measures method-call times.

    import static net.mindview.util.Print.*;
    
     
    
    interface Interface {
    
      void doSomething();
    
      void somethingElse(String arg);
    
    }
    
     
    
    class RealObject implements Interface {
    
      public void doSomething() { print("doSomething"); }
    
      public void somethingElse(String arg) {
    
        print("somethingElse " + arg);
    
      }
    
    }	
    
     
    
    class SimpleProxy implements Interface {
    
        private static int count=0;
    
        private static int scount=0;
    
      private Interface proxied;
    
      public SimpleProxy(Interface proxied) {
    
        this.proxied = proxied;
    
      }
    
      public void doSomething() {
    
        print("SimpleProxy doSomething");
    
        proxied.doSomething();
    
        print(++count);
    
      }
    
      public void somethingElse(String arg) {
    
        print("SimpleProxy somethingElse " + arg);
    
        proxied.somethingElse(arg);
    
        print(++scount);
    
      }
    
    }	
    
     
    
    class Ja14_21 {
    
      public static void consumer(Interface iface) {
    
        iface.doSomething();
    
        iface.somethingElse("bonobo");
    
      }
    
      public static void main(String[] args) {
    
        consumer(new RealObject());
    
        consumer(new SimpleProxy(new RealObject()));
    
      }
    
    }
    

    22 Modify SimpleDynamicProxy.java so that it measures method-call times.

    import java.lang.reflect.*;
    
     
    
    class DynamicProxyHandler implements InvocationHandler {
    
      private Object proxied;
    
      public DynamicProxyHandler(Object proxied) {
    
        this.proxied = proxied;
    
      }
    
      public Object
    
      invoke(Object proxy, Method method, Object[] args)
    
      throws Throwable {
    
        System.out.println("**** proxy: " + proxy.getClass() +
    
          ", method: " + method + ", args: " + args);
    
        if(args != null)
    
          for(Object arg : args)
    
            System.out.println("  " + arg);
    
        return method.invoke(proxied, args);
    
      }
    
    }	
    
     
    
    class Ja14_22 {
    
      public static void consumer(Interface iface) {
    
        iface.doSomething();
    
        iface.somethingElse("bonobo");
    
      }
    
      public static void main(String[] args) {
    
        RealObject real = new RealObject();
    
        SimpleProxy sim=new SimpleProxy(real);
    
        consumer(sim);
    
        // Insert a proxy and call again:
    
        Interface proxy = (Interface)Proxy.newProxyInstance(
    
          Interface.class.getClassLoader(),
    
          new Class[]{ Interface.class },
    
          new DynamicProxyHandler(sim));
    
        consumer(proxy);
    
      }
    
    }
    

    23 Inside invoke() in SimpleDynamicProxy.java, try to print the proxy argument and explain what happens.

    import java.lang.reflect.*;
    
     
    
    class DynamicProxyHandler implements InvocationHandler {
    
      private Object proxied;
    
      public DynamicProxyHandler(Object proxied) {
    
        this.proxied = proxied;
    
      }
    
      public Object  invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
        System.out.println("**** proxy: " + proxy.getClass() +
    
          ", method: " + method + ", args: " + args);
    
        if(args != null)
    
          for(Object arg : args)
    
            System.out.println("  " + arg);
    
        System.out.println(proxy);
    
        return method.invoke(proxied, args);
    
      }
    
    }	
    
     
    
    class Ja14_23 {
    
      public static void consumer(Interface iface) {
    
        iface.doSomething();
    
        iface.somethingElse("bonobo");
    
      }
    
      public static void main(String[] args) {
    
        RealObject real = new RealObject();
    
        SimpleProxy sim=new SimpleProxy(real);
    
        consumer(sim);
    
        // Insert a proxy and call again:
    
        Interface proxy = (Interface)Proxy.newProxyInstance(
    
          Interface.class.getClassLoader(),
    
          new Class[]{ Interface.class },
    
          new DynamicProxyHandler(sim));
    
        consumer(proxy);
    
      }
    
    }
    
    //invoke调用print打印proxy,print操作又会调用invoke,产生了无限循环。
    

    24 Add Null Objects to RegisteredFactories.java.

    import typeinfo.factory.*;
    
    import java.util.*;
    
     
    
    class Part {
    
      public String toString() {
    
        return getClass().getSimpleName();
    
      }
    
      static List<Factory<? extends Part>> partFactories =
    
        new ArrayList<Factory<? extends Part>>();	
    
      static {
    
        // Collections.addAll() gives an "unchecked generic
    
        // array creation ... for varargs parameter" warning.
    
        partFactories.add(new FuelFilter.Factory());
    
        partFactories.add(new AirFilter.Factory());
    
        partFactories.add(new CabinAirFilter.Factory());
    
        partFactories.add(new OilFilter.Factory());
    
        partFactories.add(new FanBelt.Factory());
    
        partFactories.add(new PowerSteeringBelt.Factory());
    
        partFactories.add(new GeneratorBelt.Factory());
    
        partFactories.add(new NullPart.Factory());
    
      }
    
      private static Random rand = new Random(66);
    
      public static Part createRandom() {
    
        int n = rand.nextInt(partFactories.size());
    
        return partFactories.get(n).create();
    
      }
    
    }	
    
    interface Null{}
    
    class NullPart extends Part implements Null{
    
        public final static Part NULL=new NullPart();
    
        public static class Factory implements typeinfo.factory.Factory<NullPart>{
    
            public NullPart create(){return (NullPart)NULL;}
    
        }
    
        public String toString(){return "it's NullPart";}
    
    }
    
    class Filter extends Part {}
    
     
    
    class FuelFilter extends Filter {
    
      // Create a Class Factory for each specific type:
    
      public static class Factory  implements typeinfo.factory.Factory<FuelFilter> {
    
        public FuelFilter create() { return new FuelFilter(); }
    
      }
    
    }
    
     
    
    class AirFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<AirFilter> {
    
        public AirFilter create() { return new AirFilter(); }
    
      }
    
    }	
    
     
    
    class CabinAirFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<CabinAirFilter> {
    
        public CabinAirFilter create() {
    
          return new CabinAirFilter();
    
        }
    
      }
    
    }
    
     
    
    class OilFilter extends Filter {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<OilFilter> {
    
        public OilFilter create() { return new OilFilter(); }
    
      }
    
    }	
    
     
    
    class Belt extends Part {}
    
     
    
    class FanBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<FanBelt> {
    
        public FanBelt create() { return new FanBelt(); }
    
      }
    
    }
    
     
    
    class GeneratorBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<GeneratorBelt> {
    
        public GeneratorBelt create() {
    
          return new GeneratorBelt();
    
        }
    
      }
    
    }	
    
     
    
    class PowerSteeringBelt extends Belt {
    
      public static class Factory
    
      implements typeinfo.factory.Factory<PowerSteeringBelt> {
    
        public PowerSteeringBelt create() {
    
          return new PowerSteeringBelt();
    
        }
    
      }
    
    }	
    
     
    
    public class Ja14_24 {
    
      public static void main(String[] args) {
    
        for(int i = 0; i < 10; i++)
    
          System.out.println(Part.createRandom());
    
      }
    
    } 
    

    25 Create a class containing private, protected and package-access methods. * Write code to access these methods from outside of the class's package.

    import static net.mindview.util.Print.*;
    
    import java.lang.reflect.*;
    
    import typeinfo.packageaccess.*;
    
    public class Ja14_25{
    
        public static void main(String[] agrs){
    
            DD d=new DD();
    
            try{
    
                Method u=d.getClass().getDeclaredMethod("u");
    
                u.setAccessible(true);
    
            u.invoke(d);
    
            }catch(Exception e){throw new RuntimeException(e);}
    
            
    
     
    
        }
    
    }
    

    26 Implement clearSpitValve() as described in the summary.

    import polymorphism.music.Note;
    
    import java.util.*;
    
    import static net.mindview.util.Print.*;
    
     
    
    class Instrument {
    
    	void play(Note n) { print("Instrument.play() " + n); }
    
    	public String toString() { return "Instrument"; }
    
    	void adjust() { print("Adjusting Instrument"); }
    
    }
    
     
    
    class Wind extends Instrument {
    
    	void play(Note n) { print("Wind.play() " + n); }
    
    	public String toString() { return "Wind"; }
    
    	void adjust() { print("Adjusting Wind"); }
    
    	void clearSpitValve() { print("Wind clearing spit valve"); }
    
    }
    
     
    
    class Percussion extends Instrument {
    
    	void play(Note n) { print("Percussion.play() " + n); }
    
    	public String toString() { return "Percussion"; }
    
    	void adjust() { print("Adjusting Percussion"); } 
    
    }
    
     
    
    class Stringed extends Instrument {
    
    	void play(Note n) { print("Stringed.play() " + n); }
    
    	public String toString() { return "Stringed"; }
    
    	void adjust() { print("Adjusting Stringed"); } 
    
    }
    
     
    
    class Keyboard extends Instrument {
    
    	void play(Note n) { print("Keyboard.play() " + n); }
    
    	public String toString() { return "Keyboard"; }
    
    	void adjust() { print("Adjusting Keyboard"); } 
    
    }
    
     
    
    class Brass extends Wind {
    
    	void play(Note n) { print("Brass.play() " + n); }
    
    	public String toString() { return "Brass"; }
    
    	void adjust() { print("Adjusting Brass"); }
    
    	void clearSpitValve() { print("Brass clearing spit valve"); }
    
    }
    
     
    
    class Woodwind extends Wind {
    
    	void play(Note n) { print("Woodwind.play() " + n); }
    
    	public String toString() { return "Woodwind"; }
    
    	void clearSpitValve() { print("Woodwind clearing spit valve"); }
    
    }
    
     
    
    class Piano extends Keyboard {
    
    	void play(Note n) { print("Piano.play() " + n); }
    
    	public String toString() { return "Piano"; }
    
    }
    
     
    
     class RandomInstrumentGenerator {
    
    	private Random rand = new Random();
    
    	public Instrument next() {
    
    		switch(rand.nextInt(7)) {
    
    			default:
    
    			case 0: return new Wind();
    
    			case 1: return new Percussion();
    
    			case 2: return new Stringed();
    
    			case 3: return new Keyboard();
    
    			case 4: return new Brass();
    
    			case 5: return new Woodwind();
    
    			case 6: return new Piano();
    
    		}
    
    	}
    
     }
    
    public class Ja14_26 {
    
    	// Doesn't care about type, so new types
    
    	// added to the system still work right:
    
    	public static void tune(Instrument i) {
    
    		//...
    
    		i.play(Note.MIDDLE_C);
    
    	}
    
    	public static void tuneAll(Instrument[] e) {
    
    		for(Instrument i : e)
    
    			tune(i);
    
    	}
    
    	private static RandomInstrumentGenerator gen = new RandomInstrumentGenerator();	
    
    	public static void main(String[] args) {
    
    		// Upcasting during addition to the array:
    
    		Instrument[] orchestra = new Instrument[20];
    
    		// fill up orchestra array wth instruments:
    
    		for(int i = 0; i < orchestra.length; i++)
    
    			orchestra[i] = gen.next();
    
    		for(Instrument i : orchestra) {
    
    			if(i instanceof Wind) // get RTTI
    
    				((Wind)i).clearSpitValve();
    
    			i.adjust();
    
    		}
    
    		tuneAll(orchestra);
    
    	}
    
    }
    

     

    展开全文
  • java编程思想第四版中需要使用net.mindview.util包,大家可以直接到http://www.mindviewinc.com/TIJ4/CodeInstructions.html去下载,并按照所在页面的操作进行操作。当然也可以直接点击这里的链接:点击这里下载,...
  • Java编程思想第四版 书中代码 各个示例挺不多的,适合作为参考,基本不用咋看书了。
  • public class Exercise4_9 { static int fib(int n) { if(n<=2) { return 1; } return fib(n-1)+fib(n-2); } public static void main(String[] args) { for (int i = 1; i <=10;...}
  • public class Exercise5_4 { public Exercise5_4() { System.out.println("Default Constructor"); } public Exercise5_4(String s) { System.out.println(s); } public static void main(String[] args) { ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 62,046
精华内容 24,818
关键字:

java编程思想第四版

java 订阅