Java nima Java dasturlash tili


Javada construkor yaratish qoydalari


Download 1.25 Mb.
bet26/49
Sana20.01.2023
Hajmi1.25 Mb.
#1103409
1   ...   22   23   24   25   26   27   28   29   ...   49
Bog'liq
2 5420273372074344755

Javada construkor yaratish qoydalari

  1. Construktr class nomi bilan o’xshash bo’lishi kerak

  2. Constructor no aniq ma'lumot turini ega bo'lishi kerak

Construktorni ikkita turi mavjud



  1. Argumentsiz construktrlar

  2. Parametrlik construktrlar

Constructorga oddiy misol


Bu misolda argumentsiz constructr yaratildi Bike1 clasida.Obyekt yaratilishi vaqtida construktrni ishlatadi.



  1. class Bike1{

  2. Bike1(){System.out.println("Bike is created");}

  3. public static void main(String args[]){

  4. Bike1 b=new Bike1();

  5. }

  6. }



Rasimda ko’srsatilganidek java file compiler bo’lgandan keyin aftomatic default construktr yaratadi.



default constructor misol


  1. class Student3{

  2. int id;

  3. String name;



  4. void display(){System.out.println(id+" "+name);}



  5. public static void main(String args[]){

  6. Student3 s1=new Student3();

  7. Student3 s2=new Student3();

  8. s1.display();

  9. s2.display();

  10. }




 ekranda :
0 null
0 null
Parametrga ega bo’lgan constructr


  1. class Student4{

  2. int id;

  3. String name;



  4. Student4(int i,String n){

  5. id = i;

  6. name = n;

  7. }

  8. void display(){System.out.println(id+" "+name);}



  9. public static void main(String args[]){

  10. Student4 s1 = new Student4(111,"Karan");

  11. Student4 s2 = new Student4(222,"Aryan");

  12. s1.display();

  13. s2.display();

  14. }

  15. }

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



Download 1.25 Mb.

Do'stlaringiz bilan baham:
1   ...   22   23   24   25   26   27   28   29   ...   49




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling