1. you want to store the state of your object, and shut down the jvm
a. file
b.db
c. send to any other apps via network.
objet.writeObject() and object.readObject().
Because static code are loaded in when class gets loaded via classloader and at that time, no instance of that class would have got created...
hence compiler finds the issue and complains.
How to break immutability if class
1. has private fields
2. no setter method
3. proper constructor for obj creation.
but failed to.mark the class as final.
then effectively, you created your immutable class and told everyone that, use my object, wherever for all immutable features, like storing immutable object as key
but since its nit final, any class
1. can extend it.
2. provide a setter functionality for its own private varible ,hence not immutable.
3. type cast this immutable object to mutable type reference.
and start passing where you had passed your immutable object , breaking your promises.
so.mark it final, so that no one can extend it.
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}

public class MyClass {
public someReturn myMethod(){
MyOtherClass otherClassObject = new MyOtherClass();
boolean retBool = otherClassObject.otherClassMethod();
if(retBool){
// do something
}
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class) //tells powerMock we will modify MyClass to intercept calls to new somewhere inside it
public class MyClassTest{
@Test
public void test(){
MyOtherClass myMockOtherClass = createMock(MyOtherClass.class);
//this will intercept calls to "new MyOtherClass()" in MyClass
whenNew( MyOtherClass.class).withNoArguments().thenReturn( myMockOtherClass ) ); when(myMockOtherClass.otherClassMethod()).thenReturn(true);
}
Ref : https://stackoverflow.com/questions/29398283/mocking-a-local-object-inside-a-method-of-sut-using-mockito-or-powermocktio?rq=1