Java:thinging in java p158 exercise 1

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.

 1 class Test{
 2     String s1;
 3     String s2="hello world";
 4     String s3;
 5     Test(){
 6         s3="hello java";
 7     }
 8 }
 9 public class ConstructorTest {
10 
11     public static void main(String[]args){
12         
13         Test t=new Test();
14         System.out.println(t.s1);
15         System.out.println(t.s2);
16         System.out.println(t.s3);
17         
18     }
19 }

输出

null
hello world
hello java

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。