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

Constructor in Java With EXAMPLE

Java constructors with examples

Uploaded by

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

Constructor in Java With EXAMPLE

Java constructors with examples

Uploaded by

manan londhe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

7/29/2019 Constructor in Java with EXAMPLE

(/)

Constructor in Java with EXAMPLE


What is Constructor in Java?
A constructor is a special method that is used to initialize a newly created object and is
called just after the memory is allocated for the object. It can be used to initialize the objects
to desired values or default values at the time of object creation. It is not mandatory for the
coder to write a constructor for a class.

If no user-defined constructor is provided for a class, compiler initializes member variables


to its default values.

numeric data types are set to 0


char data types are set to null character(‘\0’)
reference variables are set to null

In this tutorial, you will learn-

What is Constructor in Java?


Rules for creating a Constructor
Constructor Overloading
Constructor Chaining

Rules for creating a Java Constructor

1. It has the same name as the class


2. It should not return a value not even void

Example 1: Create your First Constructor Java

Step 1) Type following code in your editor.

https://www.guru99.com/java-constructors.html 1/8
7/29/2019 Constructor in Java with EXAMPLE
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}

public void display(){


System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}

public static void main(String args[]){


Demo d1 = new Demo();
d1.display();
}
}

Step 2) Save , Run & Compile the code. Observe the output.

Output:

Inside Constructor
Value1 === 10
Value2 === 20

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter list. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Examples of valid  constructors for class Account are

Account(int a);
Account (int a,int b);
Account (String a,int b);

Example 2: To understand Constructor Overloading

Step 1) Type the code in the editor.

https://www.guru99.com/java-constructors.html 2/8
7/29/2019 Constructor in Java with EXAMPLE
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}

Step 2) Save, Compile & Run the Code.

Step 3) Error = ?. Try and debug the error before proceeding to next step.

Step 4) Every class has a default Constructor. Default Constructor for class Demo is Demo().
In case you do not provide this constructor the compiler creates it for you and initializes the
variables to default values. You may choose to override this default constructor and initialize
variables to your desired values as shown in Example 1.

But if you specify a parametrized constructor like Demo(int a), and want to use the default
constructor Demo(), it is mandatory for you to specify it.

In other words, in case your Constructor is overridden, and you want to use the default
constructor, its need to be specified.

Step 5) Uncomment line # 4-8. Save, Compile & Run the code.
https://www.guru99.com/java-constructors.html 3/8
7/29/2019 Constructor in Java with EXAMPLE
Constructor Chaining
Consider a scenario where a base class is extended by a child. Whenever an object of the
child class is created, the constructor of the parent class is invoked first. This is called
Constructor chaining.

Example 3: To understand constructor chaining

Step 1) Copy the following code into the editor.

class Demo{
int value1;
int value2;
Demo(){
value1 = 1;
value2 = 2;
System.out.println("Inside 1st Parent Constructor");
}
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Parent Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
DemoChild d1 = new DemoChild();
d1.display();
}
}
class DemoChild extends Demo{
int value3;
int value4;
DemoChild(){
//super(5);
value3 = 3;
value4 = 4;
System.out.println("Inside the Constructor of Child");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
System.out.println("Value1 === "+value3);
System.out.println("Value2 === "+value4);
}
}

https://www.guru99.com/java-constructors.html 4/8
Step 2) Run the Code. Owing to constructor
7/29/2019
chaining, when the object of child class
Constructor in Java with EXAMPLE

DemoChild is created, constructor Demo() of the parent class is invoked first and later
constructor DemoChild() of the child is created. Expected Output  =  

Inside 1st Parent Constructor


Inside the Constructor of Child
Value1 === 1
Value2 === 2
Value1 === 3
Value2 === 4

Step 3) You may observe the constructor of the parent class Demo is overridden. What if you
want to call the overridden constructor Demo(int a) instead of the default constructor
Demo() when your child object is created?

In such cases, you can use the keyword "super" to call overridden constructors of the parent
class.

Syntax:-

super();
--or--
super(parameter list);

Example: If your constructor is like Demo(String Name,int a) you will specify super("Java",5)
If used, the keyword super needs to be the first line of code in the constructor of the child
class.

Step 4) Uncomment Line # 26 and run the code. Observe the Output.

Output:

Inside 2nd Parent Constructor


Inside the Constructor of Child
Value1 === 5
Value2 === 0
Value1 === 3
Value2 === 4

 Prev (/interface-vs-abstract-class-java.html)
https://www.guru99.com/java-constructors.html
Report a Bug
Next  (/java-packages.html) 5/8
7/29/2019 Constructor in Java with EXAMPLE

YOU MIGHT LIKE:

JAVA TUTORIALS JAVA TUTORIALS JAVA TUTORIALS

(/java-string-tolowercase- (/interface-vs-abstract- (/convert-char-string-


methods.html) class-java.html) java.html)
(/java-string- (/interface-vs- (/convert-char-
tolowercase- abstract-class-java.html) string-java.html)
methods.html) Interface vs Abstract Class in How to Convert Char to
Java String toLowercase() Java: What's the Di erence? String & String to char in
and toUpperCase() Methods (/interface-vs-abstract- Java
(/java-string-tolowercase- class-java.html) (/convert-char-string-
methods.html) java.html)

JAVA TUTORIALS JAVA TUTORIALS JAVA TUTORIALS

(/string-endswith- (/string-length-method- (/string-charat-method-


method-java.html) java.html) (/string- java.html) (/string-
(/string-endswith- length-method- charat-method-
method-java.html) java.html) java.html)
String endsWith() Method in String Length() Method in String charAt() Method in
Java with Example Java with Example Java with Example
(/string-endswith-method- (/string-length-method- (/string-charat-method-
java.html) java.html) java.html)

Java Tutorials
30) Inheritance (/java-class-inheritance.html)

31) Polymorphism (/java-inheritance-polymorphism.html)

32) Abstract Method & Class (/java-abstract-class-method.html)

33) Java Interface (/java-interface.html)

34) Interface vs Abstract Class (/interface-vs-abstract-class-java.html)

35) Java Constructors (/java-constructors.html)

36) Java Packages (/java-packages.html)

37) Exception Handling (/java-exception-handling.html)

38) User-defined (/java-user-defined-exception.html)

39) Throws (/java-exception-throws.html)

40) Trick with For Loop (/foreach-loop-java.html)


https://www.guru99.com/java-constructors.html 6/8
7/29/2019 Constructor in Java with EXAMPLE

 (https://www.facebook.com/guru99com/) 
(https://twitter.com/guru99com) 
(https://www.youtube.com/channel/UC19i1XD6k88KqHlET8atqFQ)

(https://forms.aweber.com/form/46/724807646.htm)

About
About Us (/about-us.html)
Advertise with Us (/advertise-us.html)
Write For Us (/become-an-instructor.html)
Contact Us (/contact-us.html)

Career Suggestion
SAP Career Suggestion Tool (/best-sap-module.html)
Software Testing as a Career (/software-testing-career-
complete-guide.html)

Interesting
Books to Read! (/books.html)
Blog (/blog/)
Quiz (/tests.html)
eBook (/ebook-pdf.html)

Execute online
Execute Java Online (/try-java-editor.html)
Execute Javascript (/execute-javascript-online.html)
Execute HTML (/execute-html-online.html)
Execute Python (/execute-python-online.html)

© Copyright - Guru99 2019


        Privacy Policy (/privacy-policy.html)  |  Affiliate
Disclaimer (/affiliate-earning-disclaimer.html)

https://www.guru99.com/java-constructors.html 7/8
7/29/2019 Constructor in Java with EXAMPLE

https://www.guru99.com/java-constructors.html 8/8

You might also like