Menu
Coddy logo textTech

コンストラクタメソッド

CoddyのJavaジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 7/87。

constructor は、new を使ってオブジェクトを作成したときに自動的に runs する特別な method です。class と同じ名前を持ち、return type はありません。

基本的なコンストラクター

public class Book {
    private String title;
    private String author;
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

デフォルトコンストラクタ(パラメータなし)

public class Book {
    private String title;
    
    public Book() {
        this.title = "Unknown";
    }
}

The constructor がオブジェクトの状態を初期化します

Book book = new Book("1984", "Orwell");
// コンストラクタはすぐに実行され、フィールドが設定される

constructor を記述しない場合、Java はデフォルトの空の constructor を提供します。いったん任意の constructor を記述すると、デフォルトの constructor は自動的には提供されなくなります。

challenge icon

チャレンジ

中級

Book class を作成し、すべての fields を初期化する constructor を定義します:

  • private fields: titleauthor(String)、pages(int)
  • 3 つすべての値を受け取り、this を使用して割り当てる constructor
  • 各 field の getter method
  • getSummary() メソッド。"<title> by <author> (<pages> pages)" を返します

自分で試してみよう

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String title = scanner.nextLine();
        String author = scanner.nextLine();
        int pages = Integer.parseInt(scanner.nextLine());
        
        Book book = new Book(title, author, pages);
        
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Pages: " + book.getPages());
        System.out.println(book.getSummary());
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Javaオンラインコンパイラ