In systems with multiple ways to create an object (overloaded constructors), maintaining consistent initial state can be challenging. This project demonstrates how a non-static initialization block serves as a common entry point for all constructors. Regardless of whether a user chooses "Fast Registration" or "Full Profile," the system automatically assigns a default identifier before the specific constructor logic executes. This pattern promotes the "Don't Repeat Yourself" (DRY) principle and ensures mandatory setup tasks are never skipped.
- Non-static Block: Implemented a shared block to assign a default
userIdentifier. - Constructor Overloading: Created two distinct constructors (no-arg and parameterized) for different registration flows.
- Execution Order: Verified that the initialization block runs before every constructor call.
- Encapsulation: Protected the
userIdentifierfield while ensuring it is initialized for every instance.
- Java 8+ (Instance Initialization Blocks, Constructor Overloading)
- UserProfile: The core model managing user identity and profile names.
- ProfileApp: The application driver simulating different registration scenarios.
Temporary user ID assigned.
Profile created without a name.
Temporary user ID assigned.
Profile created with name: Daria
Project Structure:
JavaBasics_Task_263/
├── src/
│ └── com/yurii/pavlenko/
│ ├── UserProfile.java
│ └── ProfileApp.java
└── README.md
Code
package com.yurii.pavlenko;
public class ProfileApp {
public static void main(String[] args) {
UserProfile fastRegistration = new UserProfile();
UserProfile fullRegistration = new UserProfile("Daria");
}
}package com.yurii.pavlenko;
public class UserProfile {
private String userIdentifier;
private String userName;
{
this.userIdentifier = "DEFAULT_REG_ID";
System.out.println("Temporary user ID assigned.");
}
public UserProfile() {
System.out.println("Profile created without a name.");
}
public UserProfile(String initialName) {
this.userName = initialName;
System.out.println("Profile created with name: " + initialName);
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT