Chapter 14 - Exercise 2

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




package com.ciaoshen.thinkinjava.chapter14;
import java.util.*;


interface HasBatteries {}
interface Waterproof {}
interface Shoots {}
interface NewInterface{} //Exercise 2 additional interface

class Toy {
    // Comment out the following default constructor
    // to see NoSuchMethodError from (*1*)
    //Toy() {}
    Toy(int i) {}
}


class FancyToy extends Toy
implements HasBatteries, Waterproof, Shoots, NewInterface{
    FancyToy() { super(1); }
}


public class ToyTest {
    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("com.ciaoshen.thinkinjava.chapter14.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());
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.