Tutorialslot.com

youtube facebook twitter gmail pinterest

Constructors in Java

A constructor is invoked immediately once the object is created.The name of the constructor should be same as the class name.It does not have any return type.It is of two types:
->Default constructor
->Parameterized constructor

Default constructor
:
A constructor which is created with no arguments are called as default constructor.

Syntax:
class_name()
{

}

Example:
class con{
con()
{
System.out.println("Constructed is created");
}
public static void main(String args[])
{
con b=new con();
}
}

Output:
Constructed is created

Parameterized constructor:
A constructor which is created with the presence of arguments are called as parameterized constructor.It defines different value for each object.

Syntax:
class_name(arg1,arg2)
{
block of statements;
}

Example:
class Student
{
int id;
String name;

Student(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1 = new Student(78,"Saravanan");
Student s2 = new Student(60,"Prahaladh");
s1.display();
s2.display();
}
}

Output:
78 Saravanan
60 Prahaladh



Advertisement Powered By Google Adsense






IF YOU LIKE THIS TUTORIALS PLEASE SHARE

Share on whatsapp

POPULAR TAGS

Java java tutorials learn java java programming tutorial learn java online learning java professionals tutorials Multithreading Generics Object Oriented Language Methods Polymorphism Inheritance