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
Sample Output:
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
Sample Output:
Explanation
-
Inner
is defined inside theOuter
class. -
The inner class can directly access members of the outer class, even if they are private.
-
To use an inner class:
-
Create an object of the outer class.
-
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
Post a Comment