0% found this document useful (0 votes)
3 views

java constuctors

Uploaded by

u0495269
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java constuctors

Uploaded by

u0495269
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Constructors in Java

In Java, a constructor is a block of codes similar to the


method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is
allocated in the memory.
Java constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object.
Rules for creating Java constructor
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and
synchronized.
Types of Java constructors
There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor.
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't
have any parameter.
Syntax of default constructor:
<class_name>(){}
Parameterized constructor:
A constructor which takes parameters are called
parameterized constructor.
Syntax:
<class_name>(parameter 1,parameter2..){}
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a
class can have any number of constructors that differ in
parameter lists. The compiler differentiates these constructors
by taking into account the number of parameters in the list
and their type.
Ex:
class Student5{
int id;
String name;
int age;
Student5(){
System.out.printl(“Default”);
id=000;
name=” AAAA”;
}

Student5(int i,String n){


id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s0=new Student();
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s0.dispaly();
s1.display();
s2.display();
}}
Output:
000 AAAA
111 Karan 0
222 Aryan 25

You might also like