Menu
Coddy logo textTech

Yapıcı Metot Aşırı Yükleme

Coddy'nin Java Journey'sinin Nesne Yönelimli Programlama bölümünün bir parçası. Ders 8 / 87.

Yapıcı aşırı yükleme, farklı parametre listelerine sahip birden fazla yapıcıya sahip olmak anlamına gelir. Bir yapıcıyı diğerinden çağırmak için this() kullanın.

Birden fazla yapıcı metot

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

this() ile kurucu zincirleme

public class Book {
    private String title;
    private String author;
    private int pages;
    
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    public Book(String title, String author) {
        this(title, author, 0);  // 3 parametreli constructor'ı çağırır
    }
    
    public Book() {
        this("Unknown", "Unknown");  // 2 parametreli constructor'ı çağırır
    }
}

Kullanım

Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();

this() yapıcıdaki ilk ifade olmalıdır. Zincirleme, yapıcılar arasındaki atama mantığının yinelenmesini önler.

challenge icon

Görev

Orta

Kurucu zincirleme kullanarak Product sınıfı için üç aşırı yüklenmiş kurucu oluşturun:

  • 3 parametreli kurucu: name, price, stock
  • 2 parametreli kurucu: name, price (stock varsayılan olarak 0 olur)
  • Varsayılan kurucu: parametre yok (name = "Unknown", price = 0, stock = 0)

Kurucuları zincirlemek ve kod tekrarını önlemek için this() kullanın.

Kendin dene

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        double price = Double.parseDouble(scanner.nextLine());
        int stock = Integer.parseInt(scanner.nextLine());
        
        Product product1 = new Product(name, price, stock);
        Product product2 = new Product("Keyboard", 79.99);
        Product product3 = new Product();
        
        System.out.println("Product 1: " + product1.getName() + " - $" + product1.getPrice() + " (Stock: " + product1.getStock() + ")");
        System.out.println("Product 2: " + product2.getName() + " - $" + product2.getPrice() + " (Stock: " + product2.getStock() + ")");
        System.out.println("Product 3: " + product3.getName() + " - $" + product3.getPrice() + " (Stock: " + product3.getStock() + ")");
    }
}
quiz iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Nesne Yönelimli Programlama bölümündeki tüm dersler

Kendi başına pratik yap: Online Java derleyicisi