Immutable Class:
Immutable classes are those classes whose once object is created it can't be modified. And any modification result in creation of new Object or any change in content will create new references.
Here we will discuss about String class, as String is a Immutable class,but StringBuffer and StringBuilder are mutable class (mutable means it will not create new references/ objects when any change occurs) ,not only string but all the wrapper class (Integer,Long ,Float, Double, Short,Byte) in java are immutable class.
We can also create custom Immutable class,their are some rules to create Immutable class as described below:
- Make class final, so that any other class can not extends it.
- Make all the data members private to prevent direct access, and final so that it can initialized only once.
- Only provide getter methods.
- Initialize all the variables through constructor.
Immutable Class Example:
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | final class Immutable{ private final String url; private final String username; public Immutable(String url,String username) { this.url = url; this.username = username; } public String getUrl() { return url; } public String getUsername() { return username; } } public class ImmutableClassExample { public static void main(String[] args) { Immutable im = new Immutable("http://www.javaidentifiers.com/", "pushkar"); System.out.println(im.getUrl()); System.out.println(im.getUsername()); } } |
Output:
http://www.javaidentifiers.com/
pushkar
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Java I/O Tutorial

No comments:
Post a Comment