Bir sınıftan nesne oluşturulduğunda, nesneyi hazırlayan şekillendiren yordamlar oluşur. İşte bunlara constructor (yapıcı) adı verilir. Constructor dışarıdan veri alabilir ancak geriye değer döndürmez.
Doğrudan diğer class ile ilişki kurma:
Product product2 = new Product(); //Referans oluşturma, instance product2.id = 2; product2.name="Lenovo V15"; product2.unitPrice = 16000; product2.detail = "32 GB RAM";
Nesneler, sınıfların canlandırılmış halidir. Yani bir sınıfı ve üyeleri doğrudan kullanmak yerine ondan bir nesne üretip bunu nesne aracılığı ile kullanmayı tercih ediyoruz.
İşte bunlara constructor (yapıcı) diyoruz:
Product Class:
public class Product {
int id;
String name;
double unitPrice;
String detail;
public Product() {
System.out.println("Ben çalıştım");
}
//Constructor örneği:
public Product(int id, String name, double unitPrice, String detail) {
// this, class içerisindeki değişkeni seçmek için kullanılır.
this(); //Yukarıdaki constructor'ın çalışmasını istiyorsak.
this.id = id;
this.name = name;
this.unitPrice = unitPrice;
this.detail = detail;
}
}
Şimdi nesne üretip kullanabiliriz:
Product product1 = new Product(1, "Lenovo V14", 15000, "16 GB RAM");
https://www.ismailgursoy.com.tr/constructors-yapicilar/
https://elifyonel.wordpress.com/2019/03/03/java-egitimi-18-constructorsyapilandiricilar/