011-003-014
Constructor Chain with Default Values
Medium
Problem Description
Constructor Chain with Default Values
In this problem: You will create a UserProfile class with three constructors chained together, progressively setting default values.
Learning Objective: Understand the pattern of chaining multiple constructors with this() to progressively set default values
Overview
In a constructor chain, constructors with fewer arguments add default values and delegate to the constructor with the most arguments. Actual initialization happens only in the final constructor, completely eliminating code duplication.
Specifications
UserProfileclass:name(String),age(int),role(String) fieldsUserProfile(String name): delegates with this(name, 0, "guest")UserProfile(String name, int age): delegates with this(name, age, "member")UserProfile(String name, int age, String role): initializes all fields- Override
toString()to return profile information
Output Format
UserProfile[name=Alice, age=0, role=guest]
UserProfile[name=Bob, age=25, role=member]
UserProfile[name=Charlie, age=30, role=admin]
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up