码迷,mamicode.com
首页 > 其他好文 > 详细

类初始化和构造器初始化的区别

时间:2018-10-15 18:23:02      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:color   ISE   style   one   string   thinking   create   struct   一个   

// initialization/ConstructorTest2.java
// TIJ4 Chapter Initialization, Exercise 2, p158
/* Create a class with a String field that is initialized at the point of
* definition, and another one that is initialized by the constructor. What is
* the difference between the two approaches.
*/

class Tester2 {
    String s1;
    String s2 = "hello";
    String s3;
    Tester2() { s3 = "good-bye"; }
}

public class ConstructorTest2 {
    public static void main(String[] args) {
        Tester2 t = new Tester2();
        System.out.println("t.s1: " + t.s1);
        System.out.println("t.s2: " + t.s2);
        System.out.println("t.s3: " + t.s3);
    }
}

//out
t.s1: null
t.s2: hello
t.s3: good-bye

初始化未定义的s3被构造器的覆盖了,也就是构造器内的初始化会覆盖类初始化的域。代码来自thinking 练习题的一个大神。

类初始化和构造器初始化的区别

标签:color   ISE   style   one   string   thinking   create   struct   一个   

原文地址:https://www.cnblogs.com/caixiaoyou/p/9792036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!