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

相关文章
|
9月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
333 6
|
9月前
|
IDE Java 编译器
java编程最基础学习
Java入门需掌握:环境搭建、基础语法、面向对象、数组集合与异常处理。通过实践编写简单程序,逐步深入学习,打牢编程基础。
458 1
|
10月前
|
SQL Java 数据库
2025 年 Java 从零基础小白到编程高手的详细学习路线攻略
2025年Java学习路线涵盖基础语法、面向对象、数据库、JavaWeb、Spring全家桶、分布式、云原生与高并发技术,结合实战项目与源码分析,助力零基础学员系统掌握Java开发技能,从入门到精通,全面提升竞争力,顺利进阶编程高手。
1402 2
|
9月前
|
安全 前端开发 Java
从反射到方法句柄:深入探索Java动态编程的终极解决方案
从反射到方法句柄,Java 动态编程不断演进。方法句柄以强类型、低开销、易优化的特性,解决反射性能差、类型弱、安全性低等问题,结合 `invokedynamic` 成为支撑 Lambda 与动态语言的终极方案。
349 0
|
11月前
|
安全 Java 数据库连接
2025 年最新 Java 学习路线图含实操指南助你高效入门 Java 编程掌握核心技能
2025年最新Java学习路线图,涵盖基础环境搭建、核心特性(如密封类、虚拟线程)、模块化开发、响应式编程、主流框架(Spring Boot 3、Spring Security 6)、数据库操作(JPA + Hibernate 6)及微服务实战,助你掌握企业级开发技能。
1241 3
|
10月前
|
Java 开发者
Java并发编程:CountDownLatch实战解析
Java并发编程:CountDownLatch实战解析
631 100
|
11月前
|
安全 Java 编译器
Java类型提升与类型转换详解
本文详解Java中的类型提升与类型转换机制,涵盖类型提升规则、自动类型转换(隐式转换)和强制类型转换(显式转换)的使用场景与注意事项。内容包括类型提升在表达式运算中的作用、自动转换的类型兼容性规则,以及强制转换可能引发的数据丢失和运行时错误。同时提供多个代码示例,帮助理解byte、short、char等类型在运算时的自动提升行为,以及浮点数和整型之间的转换技巧。最后总结了类型转换的最佳实践,如避免不必要的转换、使用显式转换提高可读性、金融计算中使用BigDecimal等,帮助开发者写出更安全、高效的Java代码。
597 0
|
11月前
|
安全 IDE Java
Java记录类型(Record):简化数据载体类
Java记录类型(Record):简化数据载体类
666 143
|
11月前
|
Java 测试技术
Java浮点类型详解:使用与区别
Java中的浮点类型主要包括float和double,它们在内存占用、精度范围和使用场景上有显著差异。float占用4字节,提供约6-7位有效数字;double占用8字节,提供约15-16位有效数字。float适合内存敏感或精度要求不高的场景,而double精度更高,是Java默认的浮点类型,推荐在大多数情况下使用。两者都存在精度限制,不能用于需要精确计算的金融领域。比较浮点数时应使用误差范围或BigDecimal类。科学计算和工程计算通常使用double,而金融计算应使用BigDecimal。
3730 102
|
9月前
|
存储 算法 安全
Java集合框架:理解类型多样性与限制
总之,在 Java 题材中正确地应对多样化与约束条件要求开发人员深入理解面向对象原则、范式编程思想以及JVM工作机理等核心知识点。通过精心设计与周密规划能够有效地利用 Java 高级特征打造出既健壮又灵活易维护系统软件产品。
235 7