Java Constructor

Constructor:

Constructor is a special type of method that is used to initialize the object.

Properties of constructor:

  • Has the same name that the class belong to.
  • Has no return type.
  • Called automatically.
  • Default constructor (no parameter) , Parametrized constructor
Code:

  1. public class EmployeeC {  
  2.       
  3.     int eid;  
  4.     String ename;  
  5.     String egender;  
  6.     String edept;  
  7.     //Parameterized Constructor implementation  
  8.     public EmployeeC(int id,String name,String gender,String dept) {  
  9.         eid=id;  
  10.         ename=name;  
  11.         egender=gender;  
  12.         edept=dept;  
  13.     }  
  14.       
  15.     public void showData() {  
  16.         System.out.println("\nEmployee_id: "+eid+"\nEmployee_name: "+ename+"\nEmployee_gender: "+egender+"\nEmployee_department: "+edept);  
  17.     }  
  18.   
  19. }  
  20.   
  21.   
  22. // Main class  
  23.   
  24.   
  25. public class ConstractorDemo {  
  26.   
  27.     public static void main(String[] args) {  
  28.         // TODO Auto-generated method stub  
  29.         EmployeeC emp1=new EmployeeC(101,"Sujan Hasan","Male","IT");  
  30.         emp1.showData();  
  31.           
  32.         EmployeeC emp2=new EmployeeC(100,"Shimul Hossain","Male","Marketing");  
  33.         emp2.showData();  
  34.           
  35.         EmployeeC emp3=new EmployeeC(102,"Shakil Sorker","Male","Networking");  
  36.         emp3.showData();  
  37.   
  38.     }  
  39.   
  40. }  
Share:

0 Comments:

Post a Comment