java编程思想第四版第十四章 类型信息习题

简介: 运行结果: 不可以向下转型到Circle
  1. fda


  1. dfa


  1. 第三题u


package net.mindview.typeinfo.test4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
abstract class Shape {
    void draw(){
        /*
         * 重点在这里: 
         * this指代的是实例对象,由于使用+连接字符串, 会自动调用对象的toString()方法.
         */
        System.out.println(this + ".draw()");
    }
    public abstract String toString();
}
class Circle extends Shape{
    @Override
    public String toString() {
        return "Circle";
    }
}
class Square extends Shape{
    @Override
    public String toString() {
        return "Square";
    }
}
class Triangle extends Shape{
    @Override
    public String toString() {
        return "Triangle";
    }
}
//菱形
class Rhomboid extends Shape{
    @Override
    public String toString() {
        return "Rhomboid";
    }
}
public class Shapes {
    public static void main(String[] args) {
        List<Shape> shapes = new ArrayList<Shape>(Arrays.asList(
            new Circle(), new Square(), new Triangle(), new Rhomboid()));
        for(Shape shape:shapes){
            shape.draw();
        }
        for(int i=0;i<shapes.size(); i++){
            Shape shape = shapes.get(i);
            if(i == 3){
                Rhomboid r = (Rhomboid)shape;
                Circle c = (Circle)shape;
            }
        }
    }


运行结果:


Circle.draw()
Square.draw()
Exception in thread "main" Triangle.draw()
Rhomboid.draw()
java.lang.ClassCastException: net.mindview.typeinfo.test4.Rhomboid cannot be cast to net.mindview.typeinfo.test4.Circle
    at net.mindview.typeinfo.test4.Shapes.main(Shapes.java:63)


不可以向下转型到Circle


4.第四题


package net.mindview.typeinfo.test4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
abstract class Shape {
    void draw(){
        /*
         * 重点在这里: 
         * this指代的是实例对象,由于使用+连接字符串, 会自动调用对象的toString()方法.
         */
        System.out.println(this + ".draw()");
    }
    public abstract String toString();
}
class Circle extends Shape{
    @Override
    public String toString() {
        return "Circle";
    }
}
class Square extends Shape{
    @Override
    public String toString() {
        return "Square";
    }
}
class Triangle extends Shape{
    @Override
    public String toString() {
        return "Triangle";
    }
}
//菱形
class Rhomboid extends Shape{
    @Override
    public String toString() {
        return "Rhomboid";
    }
}
public class Shapes {
    public static void main(String[] args) {
        List<Shape> shapes = new ArrayList<Shape>(Arrays.asList(
            new Circle(), new Square(), new Triangle(), new Rhomboid()));
        for(Shape shape:shapes){
            shape.draw();
        }
        for(int i=0;i<shapes.size(); i++){
            Shape shape = shapes.get(i);
            if(i == 3){
                //添加instanceof判断
                if (shape instanceof Rhomboid){
                    Rhomboid r = (Rhomboid)shape;
                }
                if(shape instanceof Circle){
                    Circle c = (Circle)shape;
                }
            }
        }
    }
                                                              }


使用Class.newInstance方法,必须有一个无参构造方法


5.第五题:


package net.mindview.typeinfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
abstract class Shape {
    void draw(){
        /*
         * 重点在这里: 
         * this指代的是实例对象,由于使用+连接字符串, 会自动调用对象的toString()方法.
         */
        System.out.println(this + ".draw()");
    }
    void rotate(){
        Class<? extends Shape> clazz = this.getClass();
        if(!clazz.getSimpleName().equals("Circle")){
            System.out.println("旋转"+ this);
        }else{
            System.out.println(this+"不需要旋转");
        }
    }
    public abstract String toString();
}
class Circle extends Shape{
    @Override
    public String toString() {
        return "Circle";
    }
}
class Square extends Shape{
    @Override
    public String toString() {
        return "Square";
    }
}
class Triangle extends Shape{
    @Override
    public String toString() {
        return "Triangle";
    }
}
//菱形
class Rhomboid extends Shape{
    @Override
    public String toString() {
        return "Rhomboid";
    }
}
public class Shapes {
    public static void main(String[] args) {
        List<Shape> shapes = new ArrayList<Shape>(Arrays.asList(
            new Circle(), new Square(), new Triangle(), new Rhomboid()));
        for(Shape shape:shapes){
            shape.draw();
            shape.rotate();
        }
        /*for(int i=0;i<shapes.size(); i++){
            Shape shape = shapes.get(i);
            if(i == 3){
                Rhomboid r = (Rhomboid)shape;
                Circle c = (Circle)shape;
            }
        }*/
    }
                                                              }


6.


7.第七题


package net.mindview.typeinfo.test8;
import java.util.HashSet;
import java.util.Set;
interface A {}
interface B {}
interface C {}
class D implements B{
    private int di=0;
    private String dname="";
    static{
        System.out.println("this is D");
    }
}
class E extends D implements A, B, C{
    private int ei=0;
    private String ename="";
    static{
        System.out.println("this is E");
    }
}
class F extends E implements A {
    private int fi=0;
    private String fname="";
    static{
        System.out.println("this is F");
    }
}
/**
 * 接受任意对象作为参数, 递归打印出该对象继承体系中所有的的类.
 * 包括继承的父类, 和实现的接口
 * 
 * 分析: 一个类智能继承一个父类, 可以实现多个接口.
 * 父类可以继承一个类,实现多个接口. 实现的接口可能和子类重复, 因此需要去重.
 * 递归实现
 * @author samsung
 *
 */
class G {
    public void printSuperClass(Class c){
        if(c == null) return ;
        System.out.println(c.getName());
        //得到这个类的接口
        Class[] interfaces = c.getInterfaces();
        for(Class interfaceClass:interfaces){
            printSuperClass(interfaceClass);
        }
        printSuperClass(c.getSuperclass());
    }
}
public class Test8 {
    public static void main(String[] args) {
        G g = new G();
        g.printSuperClass(F.class);
    }
}


运行结果:


net.mindview.typeinfo.test8.F
net.mindview.typeinfo.test8.A
net.mindview.typeinfo.test8.E
net.mindview.typeinfo.test8.A
net.mindview.typeinfo.test8.B
net.mindview.typeinfo.test8.C
net.mindview.typeinfo.test8.D
net.mindview.typeinfo.test8.B
java.lang.Object


8.第八题


package net.mindview.typeinfo.test8;
interface A {}
interface B {}
interface C {}
class D {
    static{
        System.out.println("this is D");
    }
}
class E extends D implements A, B, C{
    static{
        System.out.println("this is E");
    }
}
class F extends E {
    static{
        System.out.println("this is F");
    }
}
class G {
    public void printSuperClass(Class c){
        Class upClass = c.getSuperclass();
        try {
            System.out.println(upClass.newInstance());
        } catch (InstantiationException e) {
            System.out.println("实例化Instance 失败");
            System.exit(1);
        } catch (IllegalAccessException e) {
            System.out.println("实例化Instance 失败");
            System.exit(1);
        }
        if(upClass.getSuperclass() != null ){
            printSuperClass(upClass);
        }
    }
}
public class Test8 {
    public static void main(String[] args) {
        G g = new G();
        g.printSuperClass(F.class);
    }
}


运行结果:


this is D
this is E
net.mindview.typeinfo.test8.E@17cb0a16
net.mindview.typeinfo.test8.D@1303368e
java.lang.Object@37f2ae62


9.第九题


package net.mindview.typeinfo.test9;
import java.lang.reflect.Field;
interface A {}
interface B {}
interface C {}
class D {
    public int i=0;
    public String name="";
    static{
        System.out.println("this is D");
    }
}
class E extends D implements A, B, C{
    public int i=0;
    public String name="";
    static{
        System.out.println("this is E");
    }
}
class F extends E {
    public int i=0;
    public String name="";
    static{
        System.out.println("this is F");
    }
}
class G {
    public void printSuperClass(Class c){
        Class upClass = c.getSuperclass();
        try {
            //获取类中的字段
            Field[] fs = upClass.getDeclaredFields();
            System.out.println(fs.length);
            for(Field f:fs){
                //打印字段名
                System.out.println(f.getName());
                //获取字段值
                Object value = upClass.getDeclaredField(f.getName());
                System.out.println(value);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            System.out.println(upClass.newInstance());
        } catch (InstantiationException e) {
            System.out.println("实例化Instance 失败");
            System.exit(1);
        } catch (IllegalAccessException e) {
            System.out.println("实例化Instance 失败");
            System.exit(1);
        }
        if(upClass.getSuperclass() != null ){
            printSuperClass(upClass);
        }
    }
}
public class Test9 {
    public static void main(String[] args) {
        G g = new G();
        g.printSuperClass(F.class);
    }
}


运行结果:


2
i
public int net.mindview.typeinfo.test9.E.i
name
public java.lang.String net.mindview.typeinfo.test9.E.name
this is D
this is E
net.mindview.typeinfo.test9.E@1440578d
2
i
public int net.mindview.typeinfo.test9.D.i
name
public java.lang.String net.mindview.typeinfo.test9.D.name
net.mindview.typeinfo.test9.D@26f04d94
0
java.lang.Object@38a3c5b6


10.第十题


package net.mindview.typeinfo.test10;
class Pot{}
public class  Test10 {
    public static void judgeType(Object c){
        Class arrType = c.getClass().getComponentType();
        System.out.println(arrType.getName());
    }
    public static void main(String[] args) {
        judgeType(new char[10]);
        judgeType(new String[10]);
        judgeType(new long[10]);
        judgeType(new boolean[10]);
        judgeType(new Pot[10]);
    }
}


运行结果:


char
java.lang.String
long
boolean
net.mindview.typeinfo.test10.Pot


11.f


12.asf


13.a


14.第十四题


package net.mindview.typeinfo.test14;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import net.mindview.typeinfo.factory.Factory;
/**
 *  部件类
 *  
 *  比如: 有过滤器部件, 皮带部件等. 
 *  空气净化器中需要有过滤器部件, 因此要有一个制造空气净化器的过滤器的工厂
 *  汽车尾气净化器也需要有过滤器部件, 因此需要一个制造汽车尾气的过滤器的工厂
 *  
 *  皮带
 *  车轮需要皮带, 因此需要一个制造车轮的皮带的工厂
 * @author samsung
 *
 */
class Part{
    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
    //目前已注册的部件工厂
    static List<String> partNames = Arrays.asList(
            "net.mindview.typeinfo.test14.FuelFilter",
            "net.mindview.typeinfo.test14.AirFilter",
            "net.mindview.typeinfo.test14.CabinFilter",
            "net.mindview.typeinfo.test14.OilFilter",
            "net.mindview.typeinfo.test14.FanBelt",
            "net.mindview.typeinfo.test14.GeneratorBelt",
            "net.mindview.typeinfo.test14.PowerSteeringBelt"
        );
    static{
    }
    private static Random rand = new Random(47);
    //随机得到一个已注册的部件工厂, 并制造部件
    public static Part createRandom(){
        int n = rand.nextInt(partNames.size());
        try {
            return (Part) Class.forName(partNames.get(n)).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
//过滤器部件
class Filter extends Part {
}
//燃料过滤器部件
class FuelFilter extends Filter {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<FuelFilter>{
        @Override
        public FuelFilter create() {
            return new FuelFilter();
        }
    }
}
//空气净化器部件
class AirFilter extends Filter {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<AirFilter>{
        @Override
        public AirFilter create() {
            return new AirFilter();
        }
    }
}
//机舱空气过滤器部件
class CabinFilter extends Filter {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<CabinFilter>{
        @Override
        public CabinFilter create() {
            return new CabinFilter();
        }
    }
}
//燃油过滤器部件
class OilFilter extends Filter {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<OilFilter>{
        @Override
        public OilFilter create() {
            return new OilFilter();
        }
    }
}
//皮带部件
class Belt extends Part{}
//风扇皮带部件
class FanBelt extends Belt {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<FanBelt>{
        @Override
        public FanBelt create() {
            return new FanBelt();
        }
    }
}
//发动机皮带部件
class GeneratorBelt extends Belt {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<GeneratorBelt>{
        @Override
        public GeneratorBelt create() {
            return new GeneratorBelt();
        }
    }
}
//转向动力装置皮带部件
class PowerSteeringBelt extends Belt {
    public static class Factory implements net.mindview.typeinfo.factory.Factory<PowerSteeringBelt>{
        @Override
        public PowerSteeringBelt create() {
            return new PowerSteeringBelt();
        }
    }
}
/**
 * 查询目前已注册的工厂类
 * @author samsung
 *
 */
public class RegisteredFactories {
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(Part.createRandom());
        }
    }
}


15.第十五题: 内容太多, 直接参考demo


16.af


17.a


18.第十八题:


package net.mindview.typeinfo;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
public class ShowMethods {
    private ShowMethods(){}
    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 methodds invoiving 'word'";
    private static Pattern p = Pattern.compile("\\w+\\.");
    public static void main(String[] args) {
        if(args.length<1){
            System.out.println(usage);
            System.exit(1);
        }
        int lines = 0; 
        try {
            Class<?> c = Class.forName(args[0]);
            //getMethods获取的是整个继承树中所有的方法
            Method[] methods = c.getMethods();
            //获取已有的构造器
            Constructor[] ctors = c.getConstructors();
            if(args.length == 1){
                //打印所有继承树中的方法名
                for(Method method: methods){
                    System.out.println(p.matcher(method.toString()).replaceAll(""));
                }
                //打印全部构造器
                for(Constructor ctor: ctors){
                    System.out.println(p.matcher(ctor.toString()).replaceAll(""));
                }
                lines = methods.length + ctors.length;
            }else {
                //打印指定类中的方法
                for(Method method: methods){
                    if(method.toString().indexOf(args[1]) != -1){
                        System.out.println(p.matcher(method.toString()).replaceAll(""));
                        lines++;
                    }
                }
                //打印构造器
                for(Constructor ctor :ctors){
                    if(ctor.toString().indexOf(args[1])!=-1){
                        System.out.println(p.matcher(ctor.toString()).replaceAll(""));
                        lines++;
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

19.af


20.a


21.f


22.af


23.a


24.fa


25.f

相关文章
|
13天前
|
安全 算法 Java
深入理解Java并发编程:线程安全与性能优化
【4月更文挑战第11天】 在Java中,高效的并发编程是提升应用性能和响应能力的关键。本文将探讨Java并发的核心概念,包括线程安全、锁机制、线程池以及并发集合等,同时提供实用的编程技巧和最佳实践,帮助开发者在保证线程安全的前提下,优化程序性能。我们将通过分析常见的并发问题,如竞态条件、死锁,以及如何利用现代Java并发工具来避免这些问题,从而构建更加健壮和高效的多线程应用程序。
|
1天前
|
存储 Java
JAVA变量类型
JAVA变量类型
7 0
|
5天前
|
IDE Java 物联网
《Java 简易速速上手小册》第1章:Java 编程基础(2024 最新版)
《Java 简易速速上手小册》第1章:Java 编程基础(2024 最新版)
13 0
|
5天前
|
安全 Java 开发者
Java并发编程:深入理解Synchronized关键字
【4月更文挑战第19天】 在Java多线程编程中,为了确保数据的一致性和线程安全,我们经常需要使用到同步机制。其中,`synchronized`关键字是最为常见的一种方式,它能够保证在同一时刻只有一个线程可以访问某个对象的特定代码段。本文将深入探讨`synchronized`关键字的原理、用法以及性能影响,并通过具体示例来展示如何在Java程序中有效地应用这一技术。
|
6天前
|
存储 算法 安全
什么是Java泛型类型?
【4月更文挑战第13天】
12 0
什么是Java泛型类型?
|
6天前
|
安全 Java 调度
Java并发编程:深入理解线程与锁
【4月更文挑战第18天】本文探讨了Java中的线程和锁机制,包括线程的创建(通过Thread类、Runnable接口或Callable/Future)及其生命周期。Java提供多种锁机制,如`synchronized`关键字、ReentrantLock和ReadWriteLock,以确保并发访问共享资源的安全。此外,文章还介绍了高级并发工具,如Semaphore(控制并发线程数)、CountDownLatch(线程间等待)和CyclicBarrier(同步多个线程)。掌握这些知识对于编写高效、正确的并发程序至关重要。
|
7天前
|
缓存 分布式计算 监控
Java并发编程:深入理解线程池
【4月更文挑战第17天】在Java并发编程中,线程池是一种非常重要的技术,它可以有效地管理和控制线程的执行,提高系统的性能和稳定性。本文将深入探讨Java线程池的工作原理,使用方法以及在实际开发中的应用场景,帮助读者更好地理解和使用Java线程池。
|
7天前
|
Java API 数据库
深研Java异步编程:CompletableFuture与反应式编程范式的融合实践
【4月更文挑战第17天】本文探讨了Java中的CompletableFuture和反应式编程在提升异步编程体验上的作用。CompletableFuture作为Java 8引入的Future扩展,提供了一套流畅的链式API,简化异步操作,如示例所示的非阻塞数据库查询。反应式编程则关注数据流和变化传播,通过Reactor等框架实现高度响应的异步处理。两者结合,如将CompletableFuture转换为Mono或Flux,可以兼顾灵活性和资源管理,适应现代高并发环境的需求。开发者可按需选择和整合这两种技术,优化系统性能和响应能力。
|
8天前
|
缓存 监控 Java
Java并发编程:线程池与任务调度
【4月更文挑战第16天】Java并发编程中,线程池和任务调度是核心概念,能提升系统性能和响应速度。线程池通过重用线程减少创建销毁开销,如`ThreadPoolExecutor`和`ScheduledThreadPoolExecutor`。任务调度允许立即或延迟执行任务,具有灵活性。最佳实践包括合理配置线程池大小、避免过度使用线程、及时关闭线程池和处理异常。掌握这些能有效管理并发任务,避免性能瓶颈。
|
9天前
|
设计模式 运维 安全
深入理解Java并发编程:线程安全与性能优化
【4月更文挑战第15天】在Java开发中,多线程编程是提升应用程序性能和响应能力的关键手段。然而,它伴随着诸多挑战,尤其是在保证线程安全的同时如何避免性能瓶颈。本文将探讨Java并发编程的核心概念,包括同步机制、锁优化、线程池使用以及并发集合等,旨在为开发者提供实用的线程安全策略和性能优化技巧。通过实例分析和最佳实践的分享,我们的目标是帮助读者构建既高效又可靠的多线程应用。