Class Relation

A top level class cannot be declared as static ex:the following code result in a compile error

public static class Foo{

}

public class mainclass {

}


======

Immutable Class :

A class that cannot be modified after construction , every modification on a immutable object will result in a new object.Ex:class String , Integer are Immutable for example when you delete or substruct a String you get the result in another object.immutable class has only getter and not setter

Immutable class are very useful in terme of Thread Safety , no require any extern synchronization.

All fields of immutable class should be final (if not it should be only used internally by class itself and called by a final method so not accessible outside) 

another advantage of immutable class is the reusablity of the class.

disadvantage:immutable class increase garbage collector works.



example of a immutable class:

ublic final class Contacts {


    private final String name;

    private final String mobile;


    public Contacts(String name, String mobile) {

        this.name = name;

        this.mobile = mobile;

    }

  

    public String getName(){

        return name;

    }

  

    public String getMobile(){

        return mobile;

    }

}


 © Xosrov 2016