Java Constructor Example

In this post we will learn java constructor example.

Java Constructor

Java Constructor Example
Java Constructor Example

Basically constructor in java is a method, rather a special method to initialize an object. Constructor do not have any return type. Constructor name should be same as its class name.

Java Constructor Example

Read Do While Statement In Java

class Car{
public Car(){
System.out.println("Constructor example");
}
public static void main(String args[]){
Car c = new Car();
}
}

There are three types of constructor in java namely,

  • Default constructor
  • No-argument constructor
  • Parameterised constructor

Let’s see three constructor types with an example

Default Constructor

Default constructor is a constructor where you don’t define constructor in a class. That is, you do not find in the source code, rather compiler creates a default constructor. Let’s see the example for better understanding,

Default constructor Example:

class Car{
public static void main(String args[]){
Car c = new Car();
}
}

In the above example class Car has no constructor. But when above example is compiled, compiler creates one by default. Like below,

public Car(){

}

Read Java For Loop Example

No-argument constructor

is constructor with no arguments.

No- Argument Example:

class Car
{
public Car()
{
System.out.println("Car created");
}
}

Parameterised constructor

is constructor which has parameters.

Parameterised constructor Example:

class Car
{
public Car(int wheels, String name)
{
System.out.println("Parameterized Constructor Example");
}
}

About the author

admin

View all posts

Leave a Reply

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