Constructor in java

 Constructor in java

Constructors are used to initialize the object’s state.It is called when the instance of class is created.

It is special type of method which is used to intialize the object.Every time when  object is created using new() keyword at least one  constructor is called and memory is allocated to the object of the class.

If there are no constructor then java compiler provide default constructor.

  1. Class Name and constructor name must be same.
  2. Constructor does not have any return type.
  3. Java constructor can not be abstract, static, final, and synchronized.
We can use access modifiers with constructor that control object creation.

Types of constructor

There are two types of constructor

1.Default Constructor

2.Parameterized Constructor

1.Default Constructor:A constructor that does not have any parameter is called default constructor.

Syntax:

Class_Name(){}


Example of default constructor in java: 


Class Demo
{
 Demo()  //default constructor is created
{ System.out.println("constructor is called"); } public static void main() { Demo demo=new Demo();// calling a default constructor } }
2.Parameterized Constructor:A constructor that have special number of parameters is called parameterized constructor. It can have any number of parameters in constructor i.e 

Syntax:
Class_Name(int a){}

Example of Parameterised Constructor:

Class Demo
{
 Demo(String name)  //Parameterized constructor is created
{
 System.out.println("name is::"+" "+name);
}
public static void main()
{
 Demo demo=new Demo("kk");// calling a default constructor
}
}

Comments

Popular posts from this blog

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver