• Constructors are the functinalities which are going to be executed  automatically when the object is created.
  •  Can be executed only once with respect to object
  • Can't have any return type not even void.
  • Name of the constructor should and must be always name of the class.
  • Two types: default constructor and parametrized constructor

Default Constructor:

  • A Constructor that have no parameters is known as Default Constructor.

 Example program for default constructor :

  1. package com.instanceofjava;
  2.  
  3. public class MyDefaultConstructor{
  4.  
  5. public MyDefaultConstructor(){
  6.  
  7. System.out.println("I am inside default constructor");
  8.  
  9.  }
  10.  
  11. public static void main(String args[]){
  12.  
  13. MyDefaultConstructor mdc=new MyDefaultConstructor(); 
  14.  
  15. }
  16. }


Output:
  1. I am inside default constructor


Parameterized Constructor:
  • A Constructor that have parameters is known as Parameterized Constructor.
Program for Parameterized Constructor:


  1. package com.instanceofjava;
  2.  
  3. public class Employee{
  4.  
  5. private int id;
  6. private String name;
  7.  
  8. Employee(int id,String name){
  9.  this.id=id;
  10. this.name=name;
  11. }
  12.  
  13. public void display(){ 
  14.  
  15. System.out.println(id+" "+name); 
  16.  
  17. }
  18.  
  19. public static void  main (String args[]){
  20.  
  21. Emploee e=new Employee(1,"Indhu"); Employee e1=new Employee(2,"Sindhu"); e.display();
  22. e1.display();
  23.  
  24. }
  25. }


Output:
  1. 1 Indhu 
  2. 2 Sindhu


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu