Overloaded Constructors
This program demonstrates constructor overloading.
Problem Statement
Write a Java program with overloaded constructors in Student class.
Source Code
| 1 | class Student { |
| 2 | String name; int age; |
| 3 | Student(){ name="Unknown"; age=0; } |
| 4 | Student(String n,int a){ name=n; age=a; } |
| 5 | } |
| 6 | public class ConstructorOverloading { |
| 7 | public static void main(String[] args) { |
| 8 | System.out.println("Eduinq Constructor Overloading"); |
| 9 | Student s1=new Student(); |
| 10 | Student s2=new Student("Arun",20); |
| 11 | System.out.println("Student1: "+s1.name+", Age: "+s1.age); |
| 12 | System.out.println("Student2: "+s2.name+", Age: "+s2.age); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Constructor Overloading Student1: Unknown, Age: 0 Student2: Arun, Age: 20
Explanation
Multiple constructors defined. - Objects initialized differently. - Together demonstrates constructor overloading. Conclusion: Shows how to overload constructors.