OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 6 : Constructor Methods for Classes
Unit - 2
Topic - 6 : Constructor Methods for Classes
A constructor is a special method in Java that is used to initialize an object immediately upon creation.
Key Features of a Constructor
-
Has the same name as the class in which it is defined.
-
Does not have a return type (not even
void
). -
Is called automatically when an object is created.
-
Its purpose is to set up the object so it is ready to use immediately after creation.
-
The implicit return type of a constructor is the class itself.
Example: Default Constructor
Sample Output:
Types of Constructors in Java
There are two main types:
1. Default Constructor (No-Argument Constructor)
-
A constructor with no parameters.
-
Used to set default values for object properties.
Example:
Output:
2. Parameterized Constructor
-
Accepts arguments to initialize object properties with specific values.
-
Useful for assigning different values to different objects at creation time.
Example:
Output:
Key Points to Remember
-
If no constructor is defined, Java provides a default constructor automatically.
-
If you define your own constructor (default or parameterized), the automatic default constructor is not provided.
-
Constructors can be overloaded (multiple constructors with different parameter lists in the same class).
-
The main job of a constructor is object initialization, not performing logic unrelated to setup.
Comments
Post a Comment