How to implement an immutable class ?
Javasearch.buggybread.com

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

   



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

Try 2 Question(s) Test


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: