When creating objects in Java, there is a specific sequence of events. This project demonstrates the Non-Static Initialization Block. Unlike static blocks (which run once per class), non-static blocks run every time a new instance is created. Crucially, they execute after the parent constructor (if any) but before the current class's constructor logic. This is useful for shared initialization logic that must run regardless of which constructor is called.
- Non-Static Initialization: Implemented a block
{ ... }to handle pre-registration logic. - Constructor Execution: Defined a no-arg constructor to finalize the pet's entry.
- Execution Order Verification: Demonstrated that the block always precedes the constructor for every object.
- Instance Isolation: Created multiple objects to show that the initialization cycle repeats for each one.
- Java 8+ (Instance Initializers, Object Lifecycle, Constructors)
- ShelterPet: The Model. Contains both the initialization block and the constructor to show the sequence.
- SolutionApp: Entry point. Triggers the creation of two separate pet records.
We are starting registration of a new pet...
Pet entry successfully created!
We are starting registration of a new pet...
Pet entry successfully created!
Project Structure:
JavaBasics_Task_261/
├── src/
│ └── com/yurii/pavlenko/
│ ├── ShelterPet.java
│ └── SolutionApp.java
└── README.md
Code
package com.yurii.pavlenko;
public class SolutionApp {
public static void main(String[] args) {
ShelterPet first = new ShelterPet();
ShelterPet second = new ShelterPet();
}
}package com.yurii.pavlenko;
public class ShelterPet {
{
System.out.println("We are starting registration of a new pet...");
}
public ShelterPet() {
System.out.println("Pet entry successfully created!");
}
}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