Tuesday, July 30, 2019

Constructors in Java / 124 Study / by Jot Chahal

Constructors in Java

Rules for creating Java constructor

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
Java Constructors

Java Default Constructor

Syntax of default constructor:

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
Test it Now

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java default constructor

Q) What is the purpose of a default constructor?

Example of default constructor that displays the default values

Test it Now

Java Parameterized Constructor

Why use the parameterized constructor?

Example of parameterized constructor

Test it Now

Constructor Overloading in Java

Example of Constructor Overloading

Test it Now

Difference between constructor and method in Java

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be same as the class name.The method name may or may not be same as the class name.

Java Constructors vs. Methods

Java Copy Constructor

Test it Now

Copying values without constructor

Test it Now

Q) Does constructor return any value?


Can constructor perform other tasks instead of initialization?


Is there Constructor class in Java?


What is the purpose of Constructor class?

0 comments:

Post a Comment