Java Constructors

Java Constructors

A constructor in Java is a special method used to initialize objects. It is called automatically when an object is created.


1. Key Features of Constructors

  • Same name as the class

  • No return type (not even void)

  • Can have parameters

  • Used to initialize instance variables

  • Can be overloaded


2. Types of Constructors

  1. Default Constructor – No parameters; provided automatically if no constructor is defined.

  2. Parameterized Constructor – Takes parameters to initialize an object with specific values.

  3. No-Arg Constructor – A user-defined constructor without parameters (similar to default).


3. Example 1: Default Constructor


 

📌 Output:

Brand: Unknown, Year: 0

4. Example 2: Parameterized Constructor


 

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

5. Example 3: Constructor Overloading


 

📌 Output:

Area of r1 = 0
Area of r2 = 50

6. Key Points About Constructors

  • Constructor name must match the class name.

  • No return type, not even void.

  • Can be overloaded to provide multiple ways of initializing objects.

  • Automatically called when an object is created.

  • this keyword can be used to refer to current object or call another constructor.

You may also like...