How to implement an immutable class ?
Questions
Search
List By Company
List By Topic
Legacy
Tests
Repository
DashBoard
Java
Java 8
Java 7
Java Abbreviations
OCJP / SCJP
Class List
New in Java 8
Java Exceptions
Spring Exceptions
Java Enums
Java 8 Lambda
Java 8 java.time
Big Data
Best Of Java
Discussion
Search
Subscribe
Search Interview Questions
More than 3000 questions in repository.
There are more than 900 unanswered questions.
Click here
and help us by providing the answer.
Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company
Label / Company / Text
Search
Submit Question
Interview Questions and Answers
Q1.
How to implement an immutable class ?
Core Java
Ans. We can make a class immutable by
1. Making all methods and variables as private.
2. Setting variables within constructor.
Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}
and then we can initialize the object of the class as
ImmutableClass immutableObject = new ImmutableClass(5);
Now all members being private , you cant change the state of the object.
Help us improve. Please let us know the company, where you were asked this question
:
Like
Discuss
Correct / Improve
 java   oops   immutable  immutability   immutable  immutability class   technical lead
Asked in 5 Companies
intermediate
 
frequent
Correction
Duplicate of Another Question
Company where this question was Asked
Suggestion
Try 2 Question(s) Test
Which of the following class creates mutable objects ?
Boolean
File
String
StringBuffer
Which of the following class creates immutable objects ?
String
StringBuffer
StringBuilder
None of these create immutable objects.
Related Questions
What is an immutable class ?
Make the following class immutable
public class Employee {
private long employeeId;
private String employeeName;
public long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(long employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
Is immutability an advantage with Wrapper classes over primitive types ?
Which immutable classes have you worked with ? Can you name some immutable Collections ? How to make an immutable collection ?
What are the benefits of immutability or Immutable classes ?
Help us and Others Improve. Please let us know the questions asked in any of your previous interview.
Any input from you will be highly appreciated and It will unlock the application for 10 more requests.
Company Name:
Questions Asked: