如何在Java中创建不可变类?代码示例

2021年3月28日12:33:51 发表评论 551 次浏览

不可变的类意味着一旦创建了对象, 我们就无法更改其内容。在Java中, 所有包装类(例如Integer, Boolean, Byte, Short)和String类是不可变的。我们也可以创建自己的不可变类。

以下是要求:

  • 该类必须声明为最终类(这样才能创建子类)
  • 该类中的数据成员必须声明为final(这样, 在创建对象后我们就无法更改其值)
  • 参数化的构造函数
  • 所有方法的getter方法
  • 无设置器(无法选择更改实例变量的值)

创建不可变类的示例

// An immutable class
public final class Student
{
     final String name;
     final int regNo;
  
     public Student(String name, int regNo)
     {
         this .name = name;
         this .regNo = regNo;
     }
     public String getName()
     {
         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;
     }
}

输出如下:

ABC
101

在此示例中, 我们创建了一个名为Student的最终类。它具有两个最终数据成员, 一个参数化的构造函数和getter方法。请注意, 这里没有设置方法。

(为了使其起作用, 请在主函数中创建Student类的对象。)

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: