Javaでパラメーター化されたコンストラクターを作成するにはどうすればよいですか?
コンストラクターはメソッドに似ており、クラスのオブジェクトを作成するときに呼び出されます。通常、コンストラクターはクラスのインスタンス変数を初期化するために使用されます。コンストラクターはクラスと同じ名前であり、戻り型はありません。
コンストラクターには、パラメーター化されたコンストラクターと引数なしのコンストラクターの2つのタイプがあります。
パラメーター化されたコンストラクター
パラメーター化されたコンストラクターは、インスタンス変数を初期化できるパラメーターを受け入れます。パラメータ化されたコンストラクタを使用すると、クラスを個別の値でインスタンス化するときに、クラス変数を動的に初期化できます。
例
public class StudentData {
private String name;
private int age;
public StudentData(String name, int age){
this.name = name;
this.age = age;
}
public StudentData(){
this(null, 0);
}
public StudentData(String name) {
this(name, 0);
}
public StudentData(int age) {
this(null, age);
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
//Reading values from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
System.out.println(" ");
//Calling the constructor that accepts both values
System.out.println("Display method of constructor that accepts both values: ");
new StudentData(name, age).display();
System.out.println(" ");
//Calling the constructor that accepts name
System.out.println("Display method of constructor that accepts only name: ");
new StudentData(name).display();
System.out.println(" ");
//Calling the constructor that accepts age
System.out.println("Display method of constructor that accepts only age: ");
new StudentData(age).display();
System.out.println(" ");
//Calling the default constructor
System.out.println("Display method of default constructor: ");
new StudentData().display();
}
} 出力
Enter the name of the student: Krishna Enter the age of the student: 22 Display method of constructor that accepts both values: Name of the Student: Krishna Age of the Student: 22 Display method of constructor that accepts only name: Name of the Student: Krishna Age of the Student: 0 Display method of constructor that accepts only age: Name of the Student: null Age of the Student: 22
-
Java 9でProcessBuilderを使用してプロセスを作成するにはどうすればよいですか?
Java 9 ProcessHandleを追加しました プロセスAPIへのインターフェース プロセスクラスを強化します。 ProcessHandleインターフェースのインスタンスは、プロセスのステータスを照会できるようにするローカルプロセスを識別します プロセスの管理と管理、および ProcessHandle.Info PID を取得する必要があるため、ローカルコードを使用できます ローカルプロセスの。 ProcessBuilder クラスを使用して、個別のオペレーティングシステムプロセスを作成できます。以下の例では、「メモ帳」のプロセスを作成できます。 ProcessBuil
-
Java 9でHtml5準拠のJavadocを作成するにはどうすればよいですか?
Java 9より前は、特定のパッケージを見つけるためにGoogleで検索する必要があります。 、クラス 、インターフェース 、およびメソッド 情報 。 Java 9以降 、 Javadoc APIドキュメントに検索オプションが含まれています それ自体、および出力はHTML5準拠です 。 以下の例では、「 JavaDocTest.java」を作成しました。 C:/ JAVAのファイル フォルダ。 例 public class JavaDocTest { /** * Default method to be run to