instanceof java
Posts: 576
Nickname: instanceof
Registered: Jan, 2015
|
instanceof java is a java related one.
|
|
|
|
How to create immutable class in java
|
Posted: Dec 24, 2015 11:20 AM
|
|
|
This post originated from an RSS feed registered with Java Buzz
by instanceof java.
|
Original Post: How to create immutable class in java
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
|
Latest Java Buzz Posts
Latest Java Buzz Posts by instanceof java
Latest Posts From Instance Of Java
|
|
- In Java String and all wrapper classes are immutable classes.
- So how to create custom immutable class in java?
- Lets see how to make a class object immutable.
Immutable class:- Make class final so that it should not be inherited.
- All the variables should be private so should not be accessible outside of class.
- Make all variables final so that value can not be changed.
- A constructor to assign values to variables in class.
- Do not add any setter methods.
1. Java Program to create custom immutable class object in java.- package com.instaceofjava;
-
- public class ImmutableClass{
-
- private final int a;
- private final int b;
-
- ImmutableClass( int x, int y){
-
- a=x;
- b=y;
- }
-
- public getA(){
-
- return a;
- }
-
- public getB(){
-
- return b;
- }
-
- public static void main(String[] args) {
-
- ImmutableClass obj= new ImmutableClass(10,20);
-
- System.out.println("a="+obj.getA());
-
- System.out.println("b="+obj.getB());
-
- }
- }
Output: String class in java: Immutable
- public final class String
- implements java.io.Serializable, Comparable<String>, CharSequence
- {
-
- //String class variables
- private final char value[];
- private final int offset;
- private final int count;
- private int hash; // Default to 0
- private static final ObjectStreamField[] serialPersistentFields =
- new ObjectStreamField[0];
-
- //String class constructor
- public String(String original) {
-
- int size = original.count;
- char[] originalValue = original.value;
- char[] v;
- if (originalValue.length > size) {
- // The array representing the String is bigger than the new
- // String itself. Perhaps this constructor is being called
- // in order to trim the baggage, so make a copy of the array.
- int off = original.offset;
- v = Arrays.copyOfRange(originalValue, off, off+size);
- } else {
- // The array representing the String is the same
- // size as the String, so no point in making a copy.
- v = originalValue;
- }
- this.offset = 0;
- this.count = size;
- this.value = v;
- }
- }
Read: How to create immutable class in java
|
|