- 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 :
- package com.instanceofjava;
- public class MyDefaultConstructor{
- public MyDefaultConstructor(){
- System.out.println("I am inside default constructor");
- }
- public static void main(String args[]){
- MyDefaultConstructor mdc=new MyDefaultConstructor();
- }
- }
Output:
- I am inside default constructor
- A Constructor that have parameters is known as Parameterized Constructor.
- package com.instanceofjava;
- public class Employee{
- private int id;
- private String name;
- Employee(int id,String name){
- this.id=id;
- this.name=name;
- }
- public void display(){
- System.out.println(id+" "+name);
- }
- public static void main (String args[]){
- Emploee e=new Employee(1,"Indhu"); Employee e1=new Employee(2,"Sindhu"); e.display();
- e1.display();
- }
- }
Output:
- 1 Indhu
- 2 Sindhu
No comments