Konstruktør Overbelastning inn Java
What Constructor Overloading in Java?
Java Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter list. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
Examples of valid constructors for class Account are
Account(int a); Account (int a,int b); Account (String a,int b);
Eksempel 2: For å forstå Constructor Overloading i Java
Trinn 1) Type the code in the editor.
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Trinn 2) Lagre, kompiler og kjør Code.
Trinn 3) Error = ?. Try and debug the error before proceeding to next step of Java konstruktør overbelastning
Trinn 4) Every class has a default Konstruktør i Java. Default overloaded constructor Java forum class Demo is Demo(). In case you do not provide this constructor the compiler creates it for you and initializes the variables to default values. You may choose to override this default constructor and initialize variables to your desired values as shown in Example 1.
But if you specify a parametrized constructor like Demo(int a), and want to use the default constructor Java Demo(), it is mandatory for you to specify it.
In other words, in case your overloading constructor in Java is overridden, and you want to use the default constructor Java, its need to be specified.
Trinn 5) Uncomment line # 4-8. Save, Compile & Run the code.
Hvorfor trenger vi Constructor Overloading? Java?
Constructor overloading in Java allows multiple constructors in a class, each having different parameter lists. It enhances flexibility and improves code efficiency.
- Flexibility in Object Creation: Constructor overloading allows you to initialize objects in various ways, depending on the number or type of parameters.
- Code gjenbruk: You can reuse constructor logic by calling one constructor from another using the this() keyword.
- Improved Readability: Overloaded constructors help make the code more intuitive by offering specific constructor options for different initialization needs.
- Default and Custom Initialization: Constructor overloading allows you to create both default and custom-initialized objects easily.
