Skip to main content

Create Immutable Class in Java With Example?

immutable class means if its state cannot change after it is constructed. means once we created object we cant modify exisiting object.here state means instance variable values.

In Java String and all Wrapper classes are Immutable.

Rules to create Immutable class in java

  1. declare the class final,so that we cannot create subclass.
  2. make all fields final and private.so that we cannot change the values.
  3. dont write any setter methods in class

Example


package com.practice;

public final class Account {
private final int accountId;
private final String name;
public Account(int accountId, String name) {
super();
this.accountId = accountId;
this.name = name;
}
public int getAccountId() {
return accountId;
}
public String getName() {
return name;
}


}

Popular posts from this blog

Java Primitive DataTypes

Java data types will tell us what type of data can variable hold. Ex: int x = 10; In the above variable, x can hold int data type value.so we must declare any variable with data type before we can use a variable.

Instance Variables in Java

Instance variables should declare with in the class but outside of any method or block or constructor.instance variables can accessible inside class all methods , blocks & constructors.

Angular 9 Date Pipe Example

Table of Contents what is pipe in angular? Angular Date Pipe Pre-defined Date Format Custom Date Formats what is pipe in angular? In Angular Pipes are used to transform data.Pipes will take input data and transforms input data in desired output. Symbol of Pipe : " | " Angular Date Pipe Angular DatePipe is one of built-in Pipes.DatePipe is used for Format a date value according to locale rules. Syntax {{value_expression| date [:format[:timezone[:locale]]]}} DatePipe avalibale in '@angular/common' module. Example //app.component.ts import   {   Component   }   from   '@angular/core' ; @ Component ({   selector:   'app-root',    template:   `{{dOB | date:'fullDate'}}`,    styleUrls:  ['./app.component.css'] }) expo...