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

class Box { double width; double height; double depth; // Constructor for Box Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // Method to compute volume double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String[] args) { // Create Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // Get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // Get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

Sample Output:

Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0

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:

class Bike1 { // Default constructor Bike1() { System.out.println("Bike is created"); } public static void main(String[] args) { Bike1 b = new Bike1(); // Constructor is called here } }

Output:

Bike is created

2. Parameterized Constructor

  • Accepts arguments to initialize object properties with specific values.

  • Useful for assigning different values to different objects at creation time.

Example:

class Student4 { int id; String name; // Parameterized constructor Student4(int i, String n) { id = i; name = n; } void display() { System.out.println(id + " " + name); } public static void main(String[] args) { Student4 s1 = new Student4(111, "Karan"); Student4 s2 = new Student4(222, "Aryan"); s1.display(); s2.display(); } }

Output:

111 Karan 222 Aryan

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

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies