zoukankan      html  css  js  c++  java
  • [编写高质量代码:改善java程序的151个建议]建议34:构造函数尽量简化

    通过这个例子,可以分析一下 父类 子类的变量的初始化过程:

    public abstract class Server {
        public final static int DEFAULT_PORT = 40000;
        public Server(){
            int port = getPort();
            System.out.print(port);
        }
        
        protected abstract int getPort();
     
    public class SimpleServer extends Server {
        private int port = 100;
        public SimpleServer(int port) {
            this.port = port;
        }
        protected int getPort() {
            return Math.random() > 0.5 ? port : DEFAULT_PORT;
        }
    }
     
    public class Client {
        public static void main(String[] args) {
            Server s = new SimpleServer(1000);
        }
    }
     
    //0 或 40000
    原因在于整个初始化的过程。
    1. 子类接受参数1000
    2. 调用子类构造函数,默认通过super()调用父类构造函数
    3.调用父类,先初始化静态变量,DEFAULT_PORT = 40000;
    4.调用父类构造函数中,调用getPort()方法,然后实际调用的是子类的getPort()方法
    5.根据随机数,获取port值,此时port尚未赋值,是0或者DEFAULT_PORT值为40000
    6.打印0 或40000
    7.子类的变量初始化,port=100
    8.构造函数中域变量被赋值为1000.
     
    ---修改
    public abstract class Server {
        public final static int DEFAULT_PORT = 40000;
        // public Server(){
        // // int port = getPort();
        // // System.out.print(port);
        // }
        
        protected abstract int getPort();
        protected abstract int start();
     
    public class SimpleServer extends Server {
        private int port = 100;
        public SimpleServer(int port) {
            this.port = port;
        }
        protected int getPort() {
            return Math.random() > 0.5 ? port : DEFAULT_PORT;
        }
        protected int start() {
            int port = getPort();
            System.out.print(port);
            return port;
        }
    }
     
    public class Client {
        public static void main(String[] args) {
            Server s = new SimpleServer(1000);
            s.start();
        }
    }
     
    //1000 or 40000
     
    建议:构造函数要尽量简化,对于这种涉及到父类子类牵扯到运行时的逻辑尽量不要这么使用。
     
     
  • 相关阅读:
    移动端工作心得
    小程序初探
    你可能会用到的"奇技赢巧"
    一个知乎日报pwa
    Progressive Web Applications
    Java中的基本数据类型以及装箱、拆箱
    用sql获得指定记录的空段数目和字段名称--实在想不通,这种场景应用在哪
    putIfAbsent,一个字段为空的话,将该字段设置为指定值
    PO、VO、BO、POJO、DAO、DTO都是什么对象
    Java中字符串连接符(+)和append的区别
  • 原文地址:https://www.cnblogs.com/akingseu/p/3464624.html
Copyright © 2011-2022 走看看