• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Constructor in Java and Types of Constructors in Java

July 20, 2015 by javainterviewpoint Leave a Comment

Constructor is a special method in Java which is used to initialize the object. It looks like a normal method however it is not. A normal java method will have return type whereas the constructor will not have an explicit return type. A constructor will be called during the time of object creation (i.e) when we use new keyword follow by class name.

For Example : Lets say we have class by the name “Test“, we will create object for Test class like below

Test t = new Test();

This will invoke the default constructor of the Test class.

Rules for creating a Constructors in Java

There are two important rules which has to be kept in mind before creating a constructor.

  • A Constructor name should be the same name as the class name.

Suppose if we have class Test, Then constructors name also should be “Test” and not anything else.

  • A Constructor cannot have a explicit return type

We cannot declare a constructor with return type. For example we cannot have constructor like public void Test()

Types of Java Constructors

There are two type of Constructors in Java, they are

  1. Default Constructor (or) no-arg Constructor
  2. Parameterized Constructor

Default Constructor (or) no-arg constructor

A Constructor with no parameters is called as Default Constructor or no-arg constructor. In the below code we have created the no-arg constructor which gets called during the time of object creation (Car c = new Car())

public class Car 
{
    Car()
    {
        System.out.println("Default Constructor of Car class called");
    }
    public static void main(String args[])
    {
          //Calling the default constructor
          Car c = new Car();
    }
}

Output :

Default Constructor of Car class called

Parameterized Constructor

A Constructor which has parameters in it called as Parameterized Constructors, the Parameterized constructor is used to assign different values for the different objects.  In the below example we have a parameterized constructor for the car class which set the value for the parameter “carColor”

public class Car 
{
    String carColor;
    Car(String carColor)
    {
        this.carColor = carColor;
    }
    
    public void disp()
    {
        System.out.println("Color of the Car is : "+carColor);
    }
    public static void main(String args[])
    {
        //Calling the parameterized constructor
        Car c = new Car("Blue");
        c.disp();
    }
}

Output :

Color of the Car is : Blue

Can a Constructor return any value ?

The answer is the Constructor cannot return any explicit value but implicitly it will be returning the instance of the class.

public class Car 
{
    Car()
    {
        System.out.println("Default Constructor of Car class called");
    }
    public static void main(String args[])
    {
        //Calling the default constructor
        Car c1 = new Car();
    }
}

Here we doesn’t have any explicit return type but when you instantiate the class with the syntax

 Car c1 = new Car();

We are actually creating new object by allocating memory and calling the constructor. Here, the result is clearly an instance of Class Car.

Other interesting articles which you may like …

  • Sort Objects in a ArrayList using Java Comparator
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Difference between equals() and ==
  • Difference Between Interface and Abstract Class in Java
  • Difference between fail-fast and fail-safe Iterator
  • Difference between Enumeration and Iterator ?
  • Difference between HashMap and Hashtable | HashMap Vs Hashtable
  • Java StringTokenizer Example
  • How to Reverse String in Java using String Tokenizer
  • What is the use of a Private Constructors in Java
  • Fibonacci Series Java Example
  • For Loop in Java with Example
  • For-each loop or Enhanced For loop in Java
  • Use of Class.forName in java
  • why we Use Class.forName in SQL JDBC
  • Can we Overload static methods in Java
  • Can we Override static methods in Java

Filed Under: Core Java, Java Tagged With: constructor, constructor in java, default constructor, Java, parameterized constructor

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.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·