当您可以在声明时初始化实例变量时,JAVA 中的构造函数有什么用?

问题描述

一个没有构造函数的程序:

public class Sample1 {
    int a=9;
    public static void main(String args[]) {
        Sample1 obj = new Sample1();  // I kNow this is a default constructor
        System.out.println(obj.a);
    }
}

输出:9

带有构造函数的第二个程序:

public class Sample1 {
    int a;
    Sample1(){
        a=9;
    }
    public static void main(String args[]) {
        Sample1 obj = new Sample1();
        System.out.println(obj.a);
    }
}

输出:9

如果两者都给出相同的输出,那么痛苦地声明构造函数有什么用?

解决方法

对于这个用例,确实没有太大区别。构造函数通常在两种情况下很有用:

  1. 当您想要使用参数而不是将成员初始化为硬编码值时。
  2. 如果您想在构造实例时运行某些逻辑。
,

这是密切相关的,尽管它主要指的是静态的: Difference between the static initializer block and regular static initialization

所以在几个要点中:

  • 本质上,对你来说,它们是平等的
  • 首先初始化变量,然后运行 ​​CTOR(但请注意,继承可能会出现一些差异)
  • 在两者中您都可以分配最终的 <form action="example.php" method="post" autocomplete="off"> <div class="form-row"> <label for="first"> <span>First Name:</span> <input type="text" id="first" name="first" autocomplete="off" list="autocompleteOff"> </label> </div> <div class="form-row"> <label for="last"> <span>Last Name:</span> <input type="text" id="last" name="last" autocomplete="off" list="autocompleteOff"> </label> </div> <div class="form-row"> <label for="email"> <span>E-mail:</span> <input type="text" id="email" name="email" autocomplete="off" list="autocompleteOff"> </label> </div> <div class="form-row-multiple"> <label for="multiple"> <span>Choose all that apply:</span><br> <input type="checkbox" name="multiple" id="multiple" value="Option 1"><span>Option 1</span> <input type="checkbox" name="multiple" id="multiple" value="Option 2"><span>Option 2</span> <input type="checkbox" name="multiple" id="multiple" value="Option 3"><span>Option 3</span> <input type="checkbox" name="multiple" id="multiple" value="Option 4"><span>Option 4</span> </label> </div> <div class="form-row"> <button type="submit" name="submit" id="submit"><b>Submit</b></button> </div> </form> <?php $first = remove_headers($_POST['first']); $last = remove_headers($_POST['last']); $email = remove_headers($_POST['email']); $multiple = remove_headers($_POST['multiple']); $message = "First: $first\n\n" . "Last: $last\n\n" "E-mail: $email\n\n" "Multiple: $multiple\n\n"
  • 在 CTOR 内部,您可以处理给定的参数
  • 在 CTOR 内部初始化有一个很大的优势,你可以处理异常
  • 在变量初始化中,您不能调用任何抛出已检查异常的方法(派生自 variables 但不是来自 Exception
  • 在变量初始化中,当变量初始化抛出和未检查异常 (RuntimeException,Throwable,Error) 时,您无法控制会发生什么
  • 在 CTOR 中,您还可以执行 CTOR Chaining 或引用超类 CTOR