zoukankan      html  css  js  c++  java
  • java 向上转型与向下转型

    向上转型:子类转父类

    Father father1=  new Son();

    向下转型:父类转子类

    Son son =  (Son)new Father (); // 这样是运行时会报错

    Father father1 = new Son(); Son son1 = (Son) father1; // 这样不报错

    通过写一个方法把父类转换为子类

    class Father {
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * 将当前对象转换为子类对象
         *
         * @param clazz 目标类型
         * @return 目标对象
         */
        public <T extends Father> T to(Class<T> clazz) {
            T instance;
            try {
                instance = clazz.newInstance();
            } catch (Exception e) {
                throw new IllegalArgumentException("Failed to create " + clazz.getSimpleName() + " instance.", e);
            }
    
            instance.setName(this.getName());
            return instance;
        }
    }
    public class Son extends Father {
    
        private String age;
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public static void main(String[] args) {
    
            // 子类转父类,父类再转子类
            // Father father = new Son();
            // Son son = (Son) father;
    
            // 父类直接转子类
            // Son son =  (Son)new Father (); // 运行时会报错
    
            // 父类通过方法转直接转子类
            Father father = new Father();
            Son son = father.to(Son.class);
        }
    
    }
  • 相关阅读:
    android视频录制
    UIWebView 缓存
    (Detected problems with API compatibility(visit g.co/dev/appcompat for more info)
    二、为什么要安装jdk?
    一、java为什么叫java?
    jstl标签
    J2EE(八)——myeclipse开发servlet
    J2EE(七)——myeclipse开发servlet
    J2EE(六)——servlet生命周期
    J2EE(五)——servlet初识
  • 原文地址:https://www.cnblogs.com/ooo0/p/8365660.html
Copyright © 2011-2022 走看看