Javada construkor yaratish qoydalari
Construktr class nomi bilan o’xshash bo’lishi kerak
Constructor no aniq ma'lumot turini ega bo'lishi kerak
Construktorni ikkita turi mavjud
Argumentsiz construktrlar
Parametrlik construktrlar
Constructorga oddiy misol
Bu misolda argumentsiz constructr yaratildi Bike1 clasida.Obyekt yaratilishi vaqtida construktrni ishlatadi.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Rasimda ko’srsatilganidek java file compiler bo’lgandan keyin aftomatic default construktr yaratadi.
default constructor misol
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
ekranda :
0 null
0 null
Parametrga ega bo’lgan constructr
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Ekrada:
111 Karan
222 Aryan
Bu misolda parametrga ega bo’lgan constructr yaratildi.
Constructr va method orasidagi farqlar
Constructor
|
Method
|
Constructr dan obyektni dastlabki holatini bilish uchun foydalaniladi
|
Method obyektni harakterini ifodalashda foydalaniladi
|
Constructor ma’lumot qaytarmaydi
|
Method ma’lumot qaytaradi
|
Constructr bilvosita chaqiriladi
|
Method oshkora chaqiriladi
|
Java kompilyator default constructr yaratadi agar constructr bo’lmasa
|
Kompilyatsiyada method yaratilmaydi
|
Constructr nomi class nomi bilan bir xil bo’ladi
|
Method nomi o’xshashi yokiy o;xshamasligi mumkun
|
Do'stlaringiz bilan baham: |