Java OOP
Constructors
Complete lesson for Constructors using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Constructors
Section: Java OOP. Java constructors — what they are, rules, default, no-arg, parameterized, copy and private constructors, overloading, this() and super() chaining, initialization order, and small real-life examples for each idea.
What is a constructor?
- A constructor is a special block of code that runs automatically when an object is created with
new. Its job is to initialize the new object. - It has the same name as the class and no return type, not even
void. - Real-life example: when you open a bank account, the bank fills in your name, account number, and opening balance at that moment. The account never exists without those details. That "fill in at creation" step is the constructor.
- Real-life example: a new mobile phone runs its setup screen (language, Wi-Fi, account) the first time you switch it on. It happens once, at the start of its life.
public class BankAccount {
String holder;
long accountNo;
double balance;
// constructor: same name as class, no return type
BankAccount(String holder, long accountNo, double opening) {
this.holder = holder;
this.accountNo = accountNo;
this.balance = opening;
System.out.println("Account opened for " + holder);
}
public static void main(String[] args) {
BankAccount acc = new BankAccount("Ravi", 1001L, 5000); // constructor runs here
System.out.println(acc.holder + " " + acc.accountNo + " " + acc.balance);
}
} Why we need constructors
- Without a constructor you create the object first and set every field afterwards. It is easy to forget a field and get a half-filled object.
- A constructor forces the caller to supply the required values in one step, so every object starts in a valid state.
- Real-life example: a school will not admit a student without the admission form (name, class, parent phone). The form is filled at the moment of admission, not later.
// Without a constructor: easy to forget a field
Student s1 = new Student();
s1.name = "Asha";
// forgot s1.roll -> roll silently stays 0
// With a constructor: all required data at creation time
Student s2 = new Student("Asha", 101); // cannot forget roll Rules for writing a constructor
| Rule | Valid | Invalid |
|---|---|---|
| Name must equal the class name | Student() { } | student() { } (that is a method name) |
| No return type, not even void | Student() { } | void Student() { } becomes a normal method |
| Can have any access modifier | public, protected, default, private | - |
| Cannot be static, final, abstract, or synchronized | Student() { } | static Student() { } |
this(...) or super(...) must be the first statement | Student() { this("guest"); } | Student() { x = 1; this("guest"); } |
| Can be overloaded | Student(), Student(String) | Two constructors with the same parameter types |
| Can throw exceptions | Student(String n) throws IOException | - |
| Not inherited and cannot be overridden | Child calls super(...) | Expecting new Child("x") to use the parent constructor automatically |
Types of constructors
| Type | Who writes it | Parameters | Small real-life example |
|---|---|---|---|
| Default constructor | Compiler (only if you write none) | None | Ordering "tea" with no options: you get standard tea |
| No-argument constructor | You | None | New phone starts with factory settings |
| Parameterized constructor | You | One or more | Pizza order with size and toppings |
| Copy constructor | You (Java has no built-in one) | An object of the same class | Photocopy of a filled form |
| Private constructor | You | Any | Only one principal for a school (singleton) |
Default constructor
- If a class has no constructor at all, the compiler adds an invisible no-argument constructor that only calls
super(). - Fields keep their default values:
0,0.0,false,null. - As soon as you write any constructor yourself, the compiler stops adding the default one.
- Real-life example: asking a shop for "a notebook" without details. You get the standard notebook they keep for everyone.
class Notebook {
String brand;
int pages;
// no constructor written -> compiler adds: Notebook() { super(); }
}
public class DefaultDemo {
public static void main(String[] args) {
Notebook n = new Notebook();
System.out.println(n.brand + " " + n.pages); // null 0
}
} No-argument constructor
- A constructor you write yourself with no parameters, usually to set sensible starting values.
- Real-life example: a new mobile phone comes with factory settings: brightness 50, volume 7, ringtone "Classic". Every new phone starts the same way.
public class Mobile {
int brightness;
int volume;
String ringtone;
Mobile() { // no-arg constructor
brightness = 50;
volume = 7;
ringtone = "Classic";
}
public static void main(String[] args) {
Mobile m = new Mobile();
System.out.println(m.brightness + " " + m.volume + " " + m.ringtone); // 50 7 Classic
}
} Parameterized constructor
- A constructor that accepts values so each object can start with different data.
- Use
this.field = parameterwhen the parameter has the same name as the field. - Real-life example: ordering a pizza. You say the size and the topping at the counter, and the pizza is made to that order.
public class Pizza {
String size;
String topping;
Pizza(String size, String topping) { // parameterized constructor
this.size = size;
this.topping = topping;
}
void serve() {
System.out.println(size + " pizza with " + topping);
}
public static void main(String[] args) {
new Pizza("Large", "Paneer").serve(); // Large pizza with Paneer
new Pizza("Small", "Mushroom").serve(); // Small pizza with Mushroom
}
} Constructor overloading
- A class can have several constructors with different parameter lists (number, type, or order).
- The compiler picks the one that matches the arguments you pass to
new. - Real-life example: a coffee shop. "One coffee" gives a regular coffee; "one large coffee" changes the size; "one large coffee, no sugar" changes size and sugar.
public class Coffee {
String size;
boolean sugar;
Coffee() { // regular
size = "Regular";
sugar = true;
}
Coffee(String size) { // choose size
this.size = size;
sugar = true;
}
Coffee(String size, boolean sugar) { // choose size and sugar
this.size = size;
this.sugar = sugar;
}
public String toString() { return size + (sugar ? " with sugar" : " without sugar"); }
public static void main(String[] args) {
System.out.println(new Coffee()); // Regular with sugar
System.out.println(new Coffee("Large")); // Large with sugar
System.out.println(new Coffee("Large", false)); // Large without sugar
}
} Constructor chaining with this()
this(...)calls another constructor of the same class. It must be the first statement.- Put the real work in the constructor with the most parameters, and let the shorter ones pass default values to it. No duplicated code.
- Real-life example: a train ticket. If you do not choose a class, the counter books "Sleeper" for you; if you do not choose a berth, it books "Any". Every booking finally goes through one full booking form.
public class TrainTicket {
String passenger;
String travelClass;
String berth;
TrainTicket(String passenger) {
this(passenger, "Sleeper"); // chain to 2-arg
}
TrainTicket(String passenger, String travelClass) {
this(passenger, travelClass, "Any"); // chain to 3-arg
}
TrainTicket(String passenger, String travelClass, String berth) {
this.passenger = passenger; // the only place that assigns
this.travelClass = travelClass;
this.berth = berth;
}
public String toString() { return passenger + " | " + travelClass + " | " + berth; }
public static void main(String[] args) {
System.out.println(new TrainTicket("Kiran")); // Kiran | Sleeper | Any
System.out.println(new TrainTicket("Kiran", "3AC")); // Kiran | 3AC | Any
System.out.println(new TrainTicket("Kiran", "2AC", "Lower")); // Kiran | 2AC | Lower
}
} Copy constructor
- A constructor that takes another object of the same class and copies its values into the new object.
- Java does not generate one automatically (unlike C++); you write it yourself.
- For fields that are arrays or mutable objects, copy them too (deep copy), otherwise both objects share the same array.
- Real-life example: a photocopy of a filled application form. Writing on the copy does not change the original.
import java.util.Arrays;
public class Form {
String name;
int[] marks;
Form(String name, int[] marks) {
this.name = name;
this.marks = marks;
}
Form(Form other) { // copy constructor
this.name = other.name;
this.marks = other.marks.clone(); // deep copy of the array
}
public static void main(String[] args) {
Form original = new Form("Asha", new int[]{90, 85});
Form photocopy = new Form(original);
photocopy.marks[0] = 10; // scribble on the copy
System.out.println(Arrays.toString(original.marks)); // [90, 85]
System.out.println(Arrays.toString(photocopy.marks)); // [10, 85]
}
} Differences between constructor and method
| Point | Constructor | Method |
|---|---|---|
| Purpose | Initialize a new object | Perform an action / behaviour |
| Name | Must be the same as the class | Any valid name (camelCase verb) |
| Return type | None, not even void | Required (void or a type) |
| Called | Automatically by new | Explicitly: obj.method() or Class.method() |
| How many times per object | Exactly once, at creation | Any number of times |
| Inherited | No | Yes (if visible) |
| Can be overridden | No | Yes (instance methods) |
| static / final / abstract allowed | No | Yes |
| Compiler provides one | Yes, default constructor if none written | No |
| Real-life example | Filling the admission form on joining day | Attending classes every day after joining |
Small real-life constructor examples
| Real-life situation | Class | Constructor call | What gets initialized |
|---|---|---|---|
| Opening a bank account | BankAccount | new BankAccount("Ravi", 5000) | Holder name and opening balance |
| School admission | Student | new Student("Asha", 101, "10-A") | Name, roll number, section |
| Booking a train ticket | TrainTicket | new TrainTicket("Kiran", "3AC") | Passenger, class, default berth |
| Buying a new phone | Mobile | new Mobile() | Factory settings |
| Joining a company | Employee | new Employee(501, "Meena", 45000) | Employee id, name, salary |
| Ordering a pizza | Pizza | new Pizza("Large", "Paneer") | Size and topping |
| Renting a car | Rental | new Rental("KA01AB1234", 3) | Car number and number of days |
| Library membership card | Member | new Member("M-77") | Card id, issue date set to today |
| Creating a game player | Player | new Player("Arjun") | Name, health 100, level 1 |
| Photocopying a form | Form | new Form(original) | Copy of every field (copy constructor) |
Advanced — Constructors
super() and constructors in inheritance
- Every constructor first calls a parent constructor. If you do not write
super(...), the compiler insertssuper()(no-arg). - If the parent has no no-arg constructor, the child must call
super(args)explicitly, or the code does not compile. - Constructors run from the top of the hierarchy down:
Object, then the parent, then the child. - Real-life example: building a house. The foundation is laid first, then the walls, then the roof. The child (roof) cannot be built before the parent (foundation).
class Foundation {
Foundation() { System.out.println("1. Foundation laid"); }
}
class Walls extends Foundation {
Walls() { super(); System.out.println("2. Walls built"); } // super() is optional here
}
class House extends Walls {
String owner;
House(String owner) {
// compiler inserts super() here
this.owner = owner;
System.out.println("3. Roof done for " + owner);
}
}
public class BuildDemo {
public static void main(String[] args) {
new House("Ravi");
// 1. Foundation laid
// 2. Walls built
// 3. Roof done for Ravi
}
} this() vs super()
| Point | this(...) | super(...) |
|---|---|---|
| Calls | Another constructor of the same class | A constructor of the parent class |
| Position | First statement only | First statement only |
| Inserted automatically? | Never | Yes, super() if you write neither |
| Use both in one constructor? | No: only one of them can be first | No |
| Purpose | Reuse code, supply defaults | Initialize inherited fields |
Initialization order: static block, instance block, constructor
- Static blocks and static field initializers run once, when the class is loaded.
- For every
new: parent constructor first, then instance field initializers and instance blocks in source order, then the constructor body. - Real-life example: a school is set up once (static block: building, name). Each new student goes through the gate check (instance block) and then admission (constructor).
public class School {
static String name;
static {
name = "LCG Public School";
System.out.println("Static block: school set up once");
}
int studentId = nextId(); // field initializer
{
System.out.println("Instance block: gate check for student " + studentId);
}
School() {
System.out.println("Constructor: admission done for " + studentId);
}
static int counter = 0;
static int nextId() { return ++counter; }
public static void main(String[] args) {
new School();
new School();
}
}
// Static block: school set up once
// Instance block: gate check for student 1
// Constructor: admission done for 1
// Instance block: gate check for student 2
// Constructor: admission done for 2 Private constructor and the singleton pattern
- A
privateconstructor stops other classes from callingnew. - Uses: singleton (exactly one object), utility classes with only static methods (
Math,Collections), and static factory methods. - Real-life example: a school has exactly one principal. Anyone who needs the principal goes to the office (a getter); nobody can create a second principal.
public class Principal {
private static final Principal INSTANCE = new Principal("Dr. Rao");
private final String name;
private Principal(String name) { // no outside new
this.name = name;
}
public static Principal getInstance() {
return INSTANCE;
}
public String getName() { return name; }
public static void main(String[] args) {
Principal p1 = Principal.getInstance();
Principal p2 = Principal.getInstance();
System.out.println(p1.getName()); // Dr. Rao
System.out.println(p1 == p2); // true: only one object
}
} Validation in constructors (fail fast)
- Check arguments at the start of the constructor and throw
IllegalArgumentException(orNullPointerExceptionviaObjects.requireNonNull) for bad data. - Then no invalid object can ever exist, and every method can trust the fields.
- Real-life example: an ATM refuses to open an account with a negative deposit or an empty name at the counter, instead of discovering the problem months later.
import java.util.Objects;
public class Account {
private final String holder;
private double balance;
Account(String holder, double opening) {
this.holder = Objects.requireNonNull(holder, "holder is required");
if (holder.isBlank()) throw new IllegalArgumentException("holder cannot be blank");
if (opening < 500) throw new IllegalArgumentException("minimum opening balance is 500");
this.balance = opening;
}
public static void main(String[] args) {
System.out.println(new Account("Ravi", 1000).holder); // Ravi
try {
new Account("Meena", 100);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage()); // Rejected: minimum opening balance is 500
}
}
} Immutable objects with final fields
- A
finalfield must be assigned exactly once, and only in its declaration, an instance block, or a constructor. - If every field is
private finaland there are no setters, the object can never change after construction (immutable), likeStringandLocalDate. - Real-life example: a birth certificate. The details are written once when it is issued and never edited.
public final class BirthCertificate {
private final String name;
private final java.time.LocalDate dob;
public BirthCertificate(String name, java.time.LocalDate dob) {
this.name = name;
this.dob = dob;
}
public String getName() { return name; }
public java.time.LocalDate getDob() { return dob; }
// no setters: the object can never change
} Record constructors (canonical and compact)
- A
recordgets a canonical constructor automatically, with one parameter per component. - A compact constructor (no parameter list) lets you validate or normalize values before they are assigned.
- Real-life example: a GPS coordinate. Latitude must stay between -90 and 90, so the constructor rejects anything else.
public class RecordCtor {
record Location(double lat, double lon) {
Location { // compact constructor
if (lat < -90 || lat > 90) throw new IllegalArgumentException("bad latitude");
if (lon < -180 || lon > 180) throw new IllegalArgumentException("bad longitude");
}
Location(String city) { // extra constructor must call canonical
this(city.equals("Hyderabad") ? 17.38 : 0, city.equals("Hyderabad") ? 78.48 : 0);
}
}
public static void main(String[] args) {
System.out.println(new Location(12.97, 77.59)); // Location[lat=12.97, lon=77.59]
System.out.println(new Location("Hyderabad")); // Location[lat=17.38, lon=78.48]
}
} Constructors vs static factory methods
- Many JDK classes use static factory methods instead of public constructors:
List.of,LocalDate.of,Integer.valueOf,Optional.empty.
| Point | Constructor | Static factory method |
|---|---|---|
| Name | Always the class name | Descriptive: of, from, valueOf, newInstance |
| Must create a new object? | Yes, every call | No: can return a cached object |
| Return type | Exactly that class | Can return a subtype or interface |
| Two versions with the same parameter types | Not possible | Possible with different names |
| Example | new ArrayList<>() | List.of(1, 2, 3), Integer.valueOf(5) |
Pitfall: calling overridable methods in a constructor
- The parent constructor runs before the child fields are initialized.
- If the parent constructor calls a method that the child overrides, the child version runs while child fields are still default values.
- Only call
private,static, orfinalmethods from a constructor.
class Base {
Base() { describe(); } // dangerous
void describe() { System.out.println("Base"); }
}
class Derived extends Base {
String name = "Derived";
@Override
void describe() { System.out.println("name = " + name); }
}
public class CtorPitfall {
public static void main(String[] args) {
new Derived(); // prints "name = null" because name is not set yet
}
} Tricky Interview Points
Q1) What is a constructor?
Answer A special member with the same name as the class and no return type that runs automatically when an object is created with new, to initialize that object.
Q2) Give a real-life example of a constructor.
Answer Opening a bank account: the name, account number, and opening balance are filled in at the moment the account is created. new BankAccount("Ravi", 5000) does the same for an object.
Q3) What are the types of constructors in Java?
Answer Default (compiler-generated), no-argument, parameterized, copy (user-written), and private constructors.
Q4) What is a default constructor?
Answer The no-argument constructor the compiler adds only when the class declares no constructor. It calls super() and leaves fields at default values.
Q5) Why does new Student() fail after adding Student(String name)?
Answer Writing any constructor stops the compiler from adding the default one. Add a no-arg constructor yourself if you still need it.
Q6) Can a constructor have a return type?
Answer No. If you add one, even void, it becomes an ordinary method that happens to share the class name.
Q7) What is constructor overloading?
Answer Having several constructors in one class with different parameter lists, like a coffee shop offering regular, sized, and sized-without-sugar orders.
Q8) What is constructor chaining?
Answer One constructor calling another: this(...) for the same class and super(...) for the parent. It avoids duplicate initialization code.
Q9) Can this() and super() both be used in one constructor?
Answer No. Each must be the first statement, so only one of them can appear.
Q10) Are constructors inherited? Can they be overridden?
Answer Neither. A subclass must call a parent constructor with super(...), implicitly or explicitly.
Q11) In what order do constructors run in inheritance?
Answer From the top down: Object, then the parent, then the child, like foundation, walls, and roof of a house.
Q12) Does Java have a copy constructor?
Answer Not built in. You write one yourself, such as Form(Form other), copying fields and deep-copying arrays or mutable objects.
Q13) What is the use of a private constructor?
Answer It prevents new from outside the class. Used for singletons, utility classes (Math, Collections), and static factory methods.
Q14) Can a constructor be static, final, or abstract?
Answer No. Constructors belong to object creation, are never inherited, and always have a body, so these modifiers make no sense.
Q15) Can a constructor throw an exception?
Answer Yes. It can throw unchecked exceptions for validation and declare checked ones with throws. If it throws, no object reference is returned.
Q16) What runs first: static block, instance block, or constructor?
Answer Static blocks once at class loading. Then for each new: parent constructor, instance initializers and blocks in source order, and finally the constructor body.
Q17) Why should constructors not call overridable methods?
Answer The child override runs before child fields are initialized, so it sees default values such as null or 0.
Q18) Constructor vs method?
Answer A constructor initializes a new object, has the class name, no return type, runs once per object via new, and is not inherited. A method defines behaviour, has a return type, can be called many times, and is inherited.
Simple Programs
Employee joining: parameterized constructor and display
public class Employee {
int id;
String name;
double salary;
Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
void display() {
System.out.println(id + " | " + name + " | Rs." + salary);
}
public static void main(String[] args) {
Employee e1 = new Employee(501, "Meena", 45000);
Employee e2 = new Employee(502, "Arjun", 52000);
e1.display(); // 501 | Meena | Rs.45000.0
e2.display(); // 502 | Arjun | Rs.52000.0
}
} Game player: default values with a no-arg and a named constructor
public class Player {
String name;
int health;
int level;
Player() {
this("Guest"); // chain to 1-arg
}
Player(String name) {
this.name = name;
this.health = 100; // every new player starts full
this.level = 1;
}
public String toString() { return name + " [HP " + health + ", Lv " + level + "]"; }
public static void main(String[] args) {
System.out.println(new Player()); // Guest [HP 100, Lv 1]
System.out.println(new Player("Arjun")); // Arjun [HP 100, Lv 1]
}
} Car rental: overloading with default number of days
public class Rental {
static final double RATE_PER_DAY = 1800;
String carNo;
int days;
boolean withDriver;
Rental(String carNo) { this(carNo, 1, false); }
Rental(String carNo, int days) { this(carNo, days, false); }
Rental(String carNo, int days, boolean drv) {
if (days <= 0) throw new IllegalArgumentException("days must be positive");
this.carNo = carNo;
this.days = days;
this.withDriver = drv;
}
double bill() { return days * RATE_PER_DAY + (withDriver ? days * 700 : 0); }
public static void main(String[] args) {
System.out.println(new Rental("KA01AB1234").bill()); // 1800.0
System.out.println(new Rental("KA01AB1234", 3).bill()); // 5400.0
System.out.println(new Rental("KA01AB1234", 3, true).bill()); // 7500.0
}
} Library member: constructor sets today as issue date and a unique id
import java.time.LocalDate;
public class Member {
private static int nextNo = 1;
final String cardId;
final String name;
final LocalDate issued;
final LocalDate expires;
Member(String name) {
this.cardId = "M-" + (nextNo++);
this.name = name;
this.issued = LocalDate.now();
this.expires = issued.plusYears(1);
}
public static void main(String[] args) {
Member a = new Member("Asha");
Member b = new Member("Ravi");
System.out.println(a.cardId + " " + a.name + " valid till " + a.expires);
System.out.println(b.cardId + " " + b.name + " valid till " + b.expires);
}
} Rectangle with three overloaded constructors and a copy constructor
public class Rectangle {
final double length, width;
Rectangle() { this(1, 1); } // unit square
Rectangle(double side) { this(side, side); } // square
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
Rectangle(Rectangle other) { this(other.length, other.width); } // copy
double area() { return length * width; }
public static void main(String[] args) {
Rectangle a = new Rectangle();
Rectangle b = new Rectangle(4);
Rectangle c = new Rectangle(3, 5);
Rectangle d = new Rectangle(c);
System.out.println(a.area() + " " + b.area() + " " + c.area() + " " + d.area()); // 1.0 16.0 15.0 15.0
}
} Inheritance: Person, Student, and super(args)
class Person {
String name;
int age;
Person(String name, int age) { // no no-arg constructor here
this.name = name;
this.age = age;
System.out.println("Person created: " + name);
}
}
class Student extends Person {
int roll;
Student(String name, int age, int roll) {
super(name, age); // required: Person has no no-arg constructor
this.roll = roll;
System.out.println("Student created: roll " + roll);
}
}
public class SuperDemo {
public static void main(String[] args) {
Student s = new Student("Asha", 15, 101);
System.out.println(s.name + " " + s.age + " " + s.roll);
// Person created: Asha
// Student created: roll 101
// Asha 15 101
}
} Counting objects created with a constructor
public class Visitor {
static int count;
final int token;
Visitor() {
count++;
token = count;
System.out.println("Welcome! Your token is " + token);
}
public static void main(String[] args) {
new Visitor(); // Welcome! Your token is 1
new Visitor(); // Welcome! Your token is 2
new Visitor(); // Welcome! Your token is 3
System.out.println("Visitors today: " + Visitor.count);
}
} Utility class with a private constructor
public final class GstCalculator {
private GstCalculator() { // no objects allowed
throw new AssertionError("utility class");
}
public static double withGst(double amount, double ratePercent) {
return amount + amount * ratePercent / 100;
}
public static void main(String[] args) {
System.out.println(GstCalculator.withGst(1000, 18)); // 1180.0
// new GstCalculator(); // compile error outside this class
}
} Problem Solving Tricks
- Constructor checklist: same name as the class, no return type, runs once per object.
- If you see
void ClassName(), it is a method, not a constructor. - Writing any constructor removes the default one; add a no-arg constructor if frameworks or callers still need it.
- Put all assignments in the longest constructor and make the others call it with
this(...). this(...)andsuper(...)must be the first statement, so you can use only one of them.- If the parent has no no-arg constructor, every child constructor must call
super(args). - Validate inputs at the top of the constructor; an object should never exist in an invalid state.
- Deep-copy arrays and mutable fields in a copy constructor.
- Never call overridable methods from a constructor.
- Use a
privateconstructor for singletons and utility classes. - Think of a real-life "creation moment" (admission, account opening, joining day) to decide what a constructor must receive.
Practice Programs List
- Create a
BankAccountwith a parameterized constructor for holder name and opening balance, and reject balances below 500. - Write a
Mobileclass whose no-arg constructor sets factory settings, plus a parameterized constructor for custom settings. - Write a
Coffeeclass with three overloaded constructors (regular, size, size and sugar) and print each order. - Write a
TrainTicketclass that chains three constructors withthis(...). - Write a
Rectangleclass with no-arg (1x1), one-arg (square), and two-arg constructors. - Add a copy constructor to a class with an
int[]field and prove the copy does not share the array. - Accidentally write
void Rectangle()and observe thatnew Rectangle()still uses the default constructor; then fix it. - Create
Person(with only a parameterized constructor) andStudent extends Person; make the child callsuper(name, age). - Print the order of static block, instance block, and constructor for two objects of a class.
- Make a three-level hierarchy (
Foundation,Walls,House) and print the order of constructor calls. - Implement a singleton
Principalclass with a private constructor andgetInstance(). - Write a
Playerclass whose constructor gives every new player health 100 and level 1. - Create a
record Location(double lat, double lon)with a compact constructor that validates the ranges. - List five real-life "creation moments" (such as hospital registration) and write a constructor signature for each.