简体   繁体   English

java中的默认构造函数如何被调用?

[英]how default constructor in java gets called?

public class Hello {

  int i;
  char ch;
   Hello(int x){
    i=x;

   }
    Hello(char c){
     ch=c;
     }  

   public static void main(String[] args) {
  Hello h=new Hello(1);
   System.out.printf("value of i  is %d"+"value of ch is %c",h.i,h.ch);
   //Hello h=new Hello('T');
   //System.out.printf("value of i  is %d"+"value of ch is %c",h.i,h.ch);
    }

O/p is : value of i is 1value of ch is O / p是: value of i is 1value of ch is

my question is why ch value is not initialized ?? 我的问题是为什么ch值未初始化? while if the other case O/p is: value of i is 0 value of ch is T why in this case i is initialized.?? 而如果其他情况下O / p为: value of i is 0 value of ch is T为什么在这种情况下将i初始化。

You have two constructors for your class, one takes in an int and the other a char . 您的类有两个构造函数,一个构造函数采用int ,另一个构造函数为char Whichever you use to initialize an instance of your class, the other variable will use it's default value. 无论您使用哪个初始化类的实例,另一个变量都将使用它的默认值。

  • Type int defaults to 0 . 键入int默认为0
  • Type char defaults to \ , the null character, as discussed here . 键入char默认为\ ,该null字符,如讨论在这里

Therefore, when you call: 因此,当您致电:

Hello h=new Hello(1);

your results are effectively: 您的结果有效地是:

h.i = 1;
h.ch = '\u0000';

While calling: 通话时:

Hello h=new Hello('T');

effectively results in: 有效地导致:

h.i = 0;
h.ch = 'T';

Java initializes an int to 0 and a char to the null character by default. Java默认将int初始化为0,将char初始化为null字符。 Thus, System.out.println will make it seem as though there is no output for ch, but it technically has been initialized. 因此,System.out.println将使其看起来好像没有ch的输出,但从技术上讲已被初始化。 In the first case, the second constructor is not run because Hello is created by passing in an int parameter, which calls the first constructor, and as a result ch is not set to anything. 在第一种情况下,第二个构造函数不会运行,因为Hello是通过传入一个调用第一个构造函数的int参数创建的,因此ch没有设置为任何值。 The commented code behaves in the same manner, but since i is initialized to 0 by default, System.out.println shows value of i is 0 value of ch is T 注释的代码的行为方式相同,但是由于i默认情况下被初始化为0,所以System.out.println显示value of i is 0 value of ch is T

按照这种方式 ,int的默认值是0,而char的默认值是'\\ u0000'(除了null之外什么都没有),这就是您所看到的。

In Java, the default value of the int primitive type is 0 while the default char is '\', the null character. 在Java中,int基本类型的默认值为0,而默认char为'\\ u0000'(空字符)。 Which is why you aren't getting anything recognizable out of your int constructor for the value of ch. 这就是为什么您无法从int构造函数中识别出ch值的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM