OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 7 : Overloaded Constructor Methods

 

Unit - 2

Topic - 7 : Overloaded Constructor Methods

Just like normal methods, constructors in Java can be overloaded.
Overloading means having multiple constructors in the same class with different parameter lists.

This is very common in real-world applications because different objects may need to be initialized in different ways.


Example: Overloaded Constructors in Box Class

class Box { double width; double height; double depth; // Constructor with parameters Box(double w, double h, double d) { width = w; height = h; depth = d; } // Constructor with no parameters (default values) Box() { width = 1; height = 1; depth = 1; } // Constructor for a cube (single dimension) Box(double len) { width = height = depth = len; } // Method to compute volume double volume() { return width * height * depth; } } public class OverloadConsDemo { public static void main(String[] args) { // Create boxes using different constructors Box box1 = new Box(10, 20, 15); // parameterized Box box2 = new Box(); // default Box cube = new Box(7); // cube constructor // Display volumes System.out.println("Volume of box1: " + box1.volume()); System.out.println("Volume of box2: " + box2.volume()); System.out.println("Volume of cube: " + cube.volume()); } }

Sample Output:

Volume of box1: 3000.0 Volume of box2: 1.0 Volume of cube: 343.0

Key Points

  • Overloaded constructors must differ in parameter type or number.

  • They provide flexibility in creating objects.

  • You can combine default values and custom values for initialization.


Nested Classes in Java

Java allows you to define one class inside another. This is called a nested class.
If the nested class is non-static, it is called an inner class.


Example: Demonstrating an Inner Class

class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // Inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } public class InnerClassDemo { public static void main(String[] args) { Outer outer = new Outer(); outer.test(); } }

Sample Output:

display: outer_x = 100

Explanation

  • Inner is defined inside the Outer class.

  • The inner class can directly access members of the outer class, even if they are private.

  • To use an inner class:

    1. Create an object of the outer class.

    2. Create an object of the inner class through the outer class (or use it inside outer class methods).


Why Use Nested (Inner) Classes?

  • To logically group classes that are only used in one place.

  • To increase encapsulation.

  • To have more readable and maintainable code.

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