Courseiva
1Z0-811Chapter 11 of 16Objective 3.3

Constructors and Encapsulation with Access Modifiers

Constructors and encapsulation solve the problem of how to safely create and control objects in Java. Without them, every bit of data inside every object would be exposed to accidental or malicious changes, leading to bugs that are nearly impossible to track down. For someone studying for the 1Z0-811 exam, mastering these two ideas is essential because they appear in almost every exam objective about classes and objects.

12 min read
Beginner
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Constructors and Encapsulation with Access Modifiers

The Hotel Room Key Analogy

A hotel corridor, early afternoon. A new guest arrives at the front desk to check in. The receptionist hands them a key card specifically for Room 307.

This key card is like a constructor. The constructor’s job is to set up a brand-new object (the room) and give it the right starting state. The receptionist doesn’t let the guest just walk into any room and start rearranging furniture. Instead, the receptionist says, “Here is your room, and here is your key. It opens only your room.”

The room itself is the Java object. Inside the room are things like the bed, the minibar, and the safe. Some of those items are public — anyone with a key can use the minibar. Other things are private, like the safe. Only the room’s own staff (the object’s own methods) can open the safe. A guest can ask the front desk (a public method) to put something in the safe, but the guest cannot directly reach into the safe themselves.

Encapsulation is this protection. It hides the internal details (how the safe’s lock works, what the minibar’s stock system is) and only allows controlled access through published interfaces (the key card, the front desk). Access modifiers — public and private — are like the hotel’s rules: public means any key holder can use that feature; private means only the room itself can touch that area.

When a guest leaves, the constructor’s job is done. The next guest will get a fresh room with a clean starting state, set up by a new constructor call.

How It Actually Works

A constructor is a special method inside a class that Java runs automatically whenever you create a new object with the 'new' keyword. Its job is to set up the initial state of that object — giving values to the object’s variables, preparing resources, and making sure the object is ready to be used safely.

Constructors look just like methods, but with a few strict rules:

They must have the exact same name as the class.

They cannot have a return type — not even 'void'.

They can accept parameters, just like normal methods, to let you pass in starting values.

If you do not write any constructor at all, Java provides a default constructor for you. This default constructor takes no arguments and sets all the object’s fields to their default values (null for objects, 0 for numbers, false for booleans). This is the source of many beginner mistakes because the default constructor exists invisibly, but when you write ANY constructor yourself, the default constructor disappears. If you still want a no-argument constructor after you have written a parameterised one, you must write it explicitly.

Encapsulation is the practice of hiding the internal data of an object and only allowing access through a controlled set of public methods. This protects the object’s integrity because the data cannot be changed in unexpected ways from outside. To achieve encapsulation in Java, you use access modifiers on your fields (variables) and methods.

There are four access modifiers in Java, but for the 1Z0-811 exam, you must understand two: public and private.

public: a public field or method is accessible from anywhere — inside the class, inside the same package, or from a completely different package in a different project.

private: a private field or method is accessible only from within the same class. No other class can see or modify it.

The typical encapsulation pattern is to make all fields private and then provide public getter and setter methods to read and write those fields in a controlled way. A getter method (usually named 'getFieldName()') returns the current value of a private field. A setter method (usually named 'setFieldName(DataType value)') allows safe updating of a private field, often with validation.

For example, imagine a class BankAccount with a private field 'balance'. You would never want outside code to directly set the balance to a negative number. Instead, you write a public method 'deposit(double amount)' that checks if the amount is positive before adding it to the balance. This is encapsulation: the balance variable stays private, but controlled access is provided through public methods.

Access modifiers also apply to constructors. A public constructor means any class can create objects of that type. A private constructor means only the class itself can create its own objects (this is used in design patterns like Singleton, which you may encounter in 1Z0-811).

Why does this matter? Without encapsulation, your program becomes a free-for-all where any part of the code can change any variable in any object. Debugging such a program is a nightmare because you never know where a value was changed. Encapsulation gives you a single point of control — all changes to a field must go through its setter, so you can add validation, logging, or transformation there.

Constructor overloading is also an important concept. You can have multiple constructors in the same class, each with a different set of parameters. This allows you to create objects in different ways — for example, a 'Person' class might have a constructor that takes only a name, and another that takes a name and an age. The correct constructor is chosen based on the arguments you pass when using 'new'.

Remember the rules:

A constructor cannot be called directly like a method. It is only executed by the 'new' operator.

A constructor cannot return a value.

If you write a constructor with parameters, the default no-argument constructor is no longer provided. You must write your own if you need it.

A class can have many constructors, as long as they have different parameter lists (constructor overloading).

In the 1Z0-811 exam, you will need to identify whether a code snippet correctly defines a constructor, whether it uses public and private correctly, and whether an object can access its own or other objects’ fields based on access modifiers.

This diagram shows how a class (Employee) hides its private fields from other classes, while exposing controlled access through public constructors, getters, and setters.

Walk-Through

1

Declare the class

You start by creating a class with the 'class' keyword and a class name. This class will serve as the blueprint for your objects. For example: 'public class Employee { ... }'.

2

Declare private fields

Inside the class, declare all the data that objects of this class will hold. Use the 'private' access modifier so that these variables can only be accessed from within the class itself. For example: 'private String name;'.

3

Write a constructor

Create a constructor that has the same name as the class and no return type. Use it to initialise the private fields with values passed as parameters. For example: 'public Employee(String name) { this.name = name; }'. This ensures that every Employee object is created with a name.

4

Write getter methods

For each private field that you want other code to read, write a public getter method. The name follows the pattern 'getFieldName()' and returns the value of the field. For a boolean field, the getter is often named 'isFieldName()'. This gives controlled read access to the data.

5

Write setter methods (optional)

If you want to allow other code to change the value of a private field after the object is created, write a public setter method. The name follows the pattern 'setFieldName(DataType value)'. Inside the setter, you can add validation — for example, checking that a salary is not negative before assigning it.

6

Test the class by creating objects

Write a separate class (often containing the 'main' method) that instantiates objects using 'new Employee(...)'. Try to access the private fields directly — the compiler will give an error, confirming encapsulation is working. Then use the getters and setters to interact with the object’s data safely.

What This Looks Like on the Job

Imagine you are a junior developer at a small company building a system to manage employee records. The HR manager wants to store each employee’s name, salary, department, and a secret personal identification number (PIN) for security. You are tasked with implementing the 'Employee' class.

If you made every field public, any other class in the system could directly set the salary to a negative number, change the department to gibberish, or read the secret PIN. This would be a disaster for data integrity and security.

So you use encapsulation. You declare every field as private. Then you write a public constructor that requires the employee’s full details when the object is created. This constructor ensures that no Employee object can exist without all the required information. For example:

public Employee(String name, double salary, String department, String pin)

The constructor stores the passed-in values into the private fields. Now you write public getter methods (like 'getName()', 'getSalary()', 'getDepartment()', 'getPin()') so other parts of the system can read the data. But you also write setter methods with validation. The 'setSalary()' method checks that the new salary is positive, and if it isn’t, it prints an error message or throws an exception. The 'setPin()' method might require an additional authorisation parameter — only a manager with a special code can change the PIN.

In your daily work, you would:

Write the 'Employee' class with private fields only.

Create a constructor that sets initial values, ensuring objects are always created in a valid state.

Write getter and setter methods for each field, adding validation logic where needed.

Write a separate class (like 'HRDepartment') that creates Employee objects using 'new Employee(...)' and then uses the getters and setters to manage the records.

Later, the company decides that employees in certain departments should get a default salary bonus. Instead of changing the constructor everywhere, you can modify the setter to add the bonus logic automatically. Because all salary changes go through the setter, you apply the change in one place.

A real-world IT scenario might also involve a database. The Employee data gets stored in a database. The constructor creates the object in memory; then a 'saveToDatabase()' method (which is public) accesses the private fields and writes them to the database. Because the fields are private, you are sure that no other code has tampered with the data before it is saved.

Encapsulation also helps in teams. You can change the internal implementation of a class — for example, switching from storing the employee’s full name as one String to storing a first name and last name separately — without breaking any code that uses the public getters and setters. The internal structure is hidden, so as long as the public interface stays the same, everything works.

How 1Z0-811 Actually Tests This

The 1Z0-811 exam tests constructors and encapsulation very directly. Expect multiple-choice questions where you must identify which code snippet correctly defines a constructor, or which access modifier should be used for a field to achieve encapsulation.

Exact concepts that appear frequently:

Constructor syntax: The constructor name must be identical to the class name. It must have no return type (not even void). A common trap is an answer choice that looks like a constructor but includes 'void' — that is a method, not a constructor, even if the method name matches the class name. Another trap is a constructor that returns a value (e.g., 'public int ClassName()') — this is actually a method, not a constructor.

Default constructor: If no constructor is written, Java supplies a default no-argument constructor that does nothing but set fields to default values. If any constructor is written, the default constructor disappears. A typical exam question shows a class with a parameterised constructor and asks whether a call to 'new ClassName()' will compile — it will not, because the default constructor is gone.

Access modifiers for fields: To properly encapsulate, you should declare fields as 'private'. A question might show a class with a public field and ask which is the best design choice. The correct answer is to make the field private and provide public getter/setter methods.

Private constructors: A class with a private constructor cannot be instantiated from outside the class. This is tested in the context of utility classes or the Singleton pattern. A question might ask: “Which access modifier prevents the creation of objects from other classes?” The answer is a private constructor.

Getter and setter naming: Getters and setters follow the naming convention 'getFieldName()' and 'setFieldName(type value)'. For boolean fields, the getter is often named 'isFieldName()' instead of 'getFieldName()'. The exam may test whether you recognise a valid getter/setter pair.

Common traps to watch out for:

Confusing constructors with methods: A ‘method’ with no return type but that is named differently from the class is a valid method. A ‘method’ that matches the class name but has a return type is also a method, not a constructor.

Overloading the constructor: You may see a class with multiple constructors. The exam might ask which constructor is called for a given 'new' statement. You need to match the argument types to the constructor’s parameter list.

Access modifier rules: private members are not accessible from subclasses (even through inheritance). Only public and protected members are inherited (protected is not in the 1Z0-811 exam, but you should know private is not inherited). If a question shows a subclass trying to access a private field of its parent class, the code will not compile.

Package-private (default) access: If no access modifier is written, the member is package-private (accessible only within the same package). This is not explicitly tested in 1Z0-811, but you should be aware it exists so you do not confuse it with public or private.

Key definitions to memorise:

Constructor: A special method that initialises a new object. It has the same name as the class, no return type, and is invoked with the 'new' keyword.

Encapsulation: Hiding internal data and providing controlled access through public methods.

Public: Accessible from anywhere.

Private: Accessible only within the same class.

Getter: A public method that returns a private field’s value.

Setter: A public method that sets a private field’s value, often with validation.

Key Takeaways

A constructor has the exact same name as the class, no return type, and is called automatically when you use the 'new' keyword.

If you write any constructor in a class, Java removes the default no-argument constructor — you must write your own if you need it.

Private fields can only be accessed from within the same class, never from other classes, even in the same package.

To properly encapsulate a field, make it private and provide public getter and setter methods to control read and write access.

Constructor overloading allows a class to have multiple constructors with different parameter lists, giving flexibility in how objects are created.

The 'this()' keyword in a constructor must be the very first statement and calls another constructor in the same class, helping avoid code duplication.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Constructor

Name must match the class name exactly.

Has no return type — not even void.

Called automatically by the 'new' keyword.

Method

Can have any name different from the class name.

Must declare a return type (can be void).

Called explicitly with method name and parentheses.

Public access modifier

Accessible from any class in any package.

Used for constructors to allow object creation from anywhere.

Used for getters and setters to expose controlled access.

Private access modifier

Accessible only from within the same class.

Used for fields to hide internal data (encapsulation).

Can be used on constructors to prevent external instantiation.

Getter method

Returns the current value of a private field.

Name pattern: getFieldName() or isFieldName() for booleans.

Takes no parameters.

Setter method

Changes the value of a private field.

Name pattern: setFieldName(DataType value).

Takes a single parameter of the field’s type.

Default constructor

Provided automatically by Java if no constructor is written.

Takes no parameters.

Does nothing except set fields to default values.

User-defined constructor

Written explicitly by the programmer.

Can take zero or many parameters.

Can initialise fields with specific values and execute custom logic.

Watch Out for These

Mistake

Constructors are inherited just like normal methods, so a subclass automatically gets the parent’s constructors.

Correct

Constructors are not inherited. A subclass must define its own constructors. If a subclass constructor does not explicitly call a parent constructor using super(), Java automatically inserts a call to the parent’s no-argument constructor.

This mistake comes from generalising the concept of inheritance. People think all members of a class are inherited, forgetting that constructors are special and belong only to the class they are written in.

Mistake

If I write no constructor in my class, the class cannot be instantiated because there is no way to initialise it.

Correct

Java automatically provides a default no-argument constructor if no constructor is written. The default constructor initialises fields to their default values (null, 0, false).

Beginners often think code only runs if they explicitly write it. The fact that Java silently adds a constructor feels like magic, so they assume it does not exist.

Mistake

I can use 'this()' inside a constructor to call another constructor from the same class, but only if I place it in the last line of the constructor.

Correct

The call to 'this()' must be the very first statement in the constructor. You cannot place it anywhere else, and you cannot add any other code before it.

Java’s syntax for constructor chaining is strict because it ensures that the object’s initialisation is done in the correct order. Beginners see examples where 'this()' is first and assume they can reorder it.

Mistake

Private fields can be accessed from any method inside the same package, as long as the method is public.

Correct

Private fields are accessible only from within the same class — not from other classes in the same package, not from subclasses, not from anywhere else. Package-level access is the default (package-private) when no modifier is written.

This confusion arises because other access modifiers (like protected and default) do allow package-level access. Beginners think ‘private’ is weaker than it actually is.

Mistake

A setter method is optional for encapsulation; as long as the field is private, the data is fully encapsulated.

Correct

Encapsulation requires both hiding the data (private field) and providing controlled access (public getter and setter if needed). Without a setter, the field cannot be changed at all after the constructor runs, which is still encapsulation — but if in an exam they ask about ‘proper encapsulation’, they expect a getter/setter pair or at least a getter.

Students hear ‘hide the data’ and stop there. They forget that ‘hide’ means prevent direct access, not prevent all access. The methods that provide access are part of the encapsulation design.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What happens if I forget to write a constructor in my Java class?

Java automatically provides a default no-argument constructor that does nothing except set all fields to their default values (null for objects, 0 for numbers, false for booleans). This default constructor only exists if you have not written any constructor yourself.

Can a constructor return a value?

No. A constructor is never allowed to have a return type, not even 'void'. If you write a return type, even 'void', it becomes a regular method, not a constructor — even if the method name matches the class name.

What is the difference between private and public?

A private member can only be accessed from inside the same class. A public member can be accessed from any other class anywhere. You use private to hide implementation details (encapsulation) and public to expose a controlled interface.

Do I need both a getter and a setter for every private field?

No. You only write a getter if you want other code to be able to read the field, and only write a setter if you want other code to be able to change it. For a field like an employee’s ID that should never change after creation, you would only provide a getter.

Why can’t I call a constructor directly like a normal method?

Constructors are designed solely to initialise new objects. They are invoked automatically by the 'new' keyword. You cannot call them like 'employee.Employee()' because they are not methods. The only way to execute a constructor is by using 'new ClassName()'.

What does 'this()' do in a constructor?

'this()' is a call to another constructor of the same class. It must be the very first statement in a constructor. It allows you to reuse code — for example, a no-argument constructor can call a parameterised constructor with default values.

Terms Worth Knowing

Keep going

You've finished Constructors and Encapsulation with Access Modifiers. Continue through the 1Z0-811 study guide to build a complete picture of the exam.

Done with this chapter?