OCJP

Constructor In Java

Constructor is a special type of function that has same name as class name. Constructor does not have any return type (not even void). It is not compulsory that Constructor must be defined as public, but practically to declare constructor as private, not too much useful as you can not use it outside the class.

class Time
{
private int hr;
private int mn;

	public Time() //No Parameterized Constructor
	{
	hr=2;
	mn=30;
	}

	public Time(int hr,int mn) //Parameterized Constructor/Construcor Overloading
	{
	this.hr=hr;
	this.mn=mn;
	}

	public void showTime() //Member Function
	{
	Date D= new Date();
	System.out.println(D);
	System.out.println("Time is "+hr+":"+mn);
	}
}

public class ConstructorDemo
{
	public static void main(String []a)
	{
	Time T = new Time();
	T.showTime();	
	
	Time T1= new Time(5,50);
	T1.showTime();
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?