JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Constructor in Java

January 19, 2014 by Krishna Srinivasan Leave a Comment

Constructors are special type of methods that are invoked at the time of creating the objects. If you use new keyword for creating the object, the constructors are called. There are certain restrictions imposed on these special type of methods.

  • Constructors should have the same name as class name
  • Constructors should not have any return type
  • There are two types of constructors.
    • Default constructor
    • Parameter used constructor
  • There can be more than one constructors for a class. It implies that constructors can be overloaded.
  • Constructor can be declared as private, default, protected and public access.
  • If you declare private constructor, then you can not create instance for that class by invoking the constructor from other classes.
  • If there is no constructor specified in a class, compiler creates default no-argument empty constructor.

Constructor Example

Look at the constructor syntax to understand it better.

[code lang=”java”]
package javabeat.net.core;

public class ConstructorDemo {
private int i;
//Default Constructor
ConstructorDemo(){
this.i = 10;
System.out.println("Default Constructor Called!");
}
//Parameter Constructor
public ConstructorDemo(int i){
this.i = i;
System.out.println("Parameter Constructor Called!");
}

public static void main (String args[]){
ConstructorDemo demo1 = new ConstructorDemo();
ConstructorDemo demo2 = new ConstructorDemo(20);
System.out.println(demo1.i);
System.out.println(demo2.i);
}
}
[/code]

Output of the above example will be:

[code]
Default Constructor Called!
Parameter Constructor Called!
10
20
[/code]

Filed Under: Java Tagged With: Java Basics

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved