package com.misc;
import java.math.BigDecimal;
import java.math.BigInteger;
public class BigDecimalImmutableTest {
public static void main(String[] args) {
SuperDecimal superDecimal = new SuperDecimal(new BigInteger("1"));
superDecimal.color = 5;
System.out.println(superDecimal.color);
}
}
class SuperDecimal extends BigDecimal {
public SuperDecimal(BigInteger bi) {
super(bi);
color = 2;
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
int color = 1;
}
output:5
Joshua mentions in the Item 15 : The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInteger and BigDecimal. But as the class is not marked as final, an untrusted client might provide an argument by subclassing the same. Why is he mentioning the class as immutable then?
本文通过一个具体的Java代码示例,深入探讨了BigDecimal类的不可变性特性,以及其子类试图修改内部状态的可能性。文章指出尽管BigDecimal本身设计为不可变,但其未标记为final可能导致子类修改其状态的问题。
1762

被折叠的 条评论
为什么被折叠?



