-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathImmutableclass.java
36 lines (33 loc) · 985 Bytes
/
Immutableclass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//Immutable class is that when once object got created for a class , its value can't be changed
//Immutable class can be created by using final keyword
//In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
public final class Student //use of final class
{
final String name; //use of final data member
final int regNo;
public Student(String name, int regNo)
{
this.name = name;
this.regNo = regNo;
}
public String getName() //no setters only getters in immutable classes
{
return name;
}
public int getRegNo()
{
return regNo;
}
}
// Driver class
class Test
{
public static void main(String args[])
{
Student s = new Student("ABC", 101);
System.out.println(s.getName());
System.out.println(s.getRegNo());
// Uncommenting below line causes error
// s.regNo = 102;
}
}