Showing posts with label Under The Hood. Show all posts
Showing posts with label Under The Hood. Show all posts

Simple Object Immutability

While most objects are mutable, some are not. For example, any bean that provides a setXXX method is
mutable. Immutable objects can be used to define values or attributes that you don't want to be changed.


Example:

public class MyConstant {
private double value;
public MyConstant(double value) {
this.value = value;
}
public double getValue() {
return value;
}

}

This is not the only way to make object immutable, this is one of the ways available.

Truth Behind String Literal

Most of the problems with using String stem from the fact that String objects are immutable. Once they've
been created, they cannot be changed. Operations that might appear to modify String objects actually generate completely new ones.

Then what happen with string literal ?
The String and StringBuffer classes are meant to be used together to overcome this situation.

Example:

String xyz = "x" + y + "z";
It automatically transforms the code to
String xyz = new StringBuffer().append("x")
                                                    .append(y)
                                                    .append("z")

                                                     .toString();


This gives you an idea how String concatenation actually works. Note that two objects are created to perform the transformation: A new StringBuffer is created explicitly and a new String is returned from toString.

Do interface really extends the member of Object class?

To know this, we'll have to know about the members of  interface.

Interface Members:

The members of an interface are:
• Those members declared in the interface.
• Those members inherited from direct superinterfaces.
• If an interface has no direct superinterfaces, then the interface implicitly declares
a public abstract member method m with signature s, return type r, and throws
clause t corresponding to each public instance method m with signature s, return
type r, and throws clause t declared in Object, unless a method with the same
signature, same return type, and a compatible throws clause is explicitly declared
by the interface.
It is a compile-time error if the interface explicitly declares such a method m in
the case where m is declared to be final in Object.
It follows that is a compile-time error if the interface declares a method with a
signature that is override-equivalent to a public method of Object, but
has a different return type or incompatible throws clause.

 
Copyright (c) 2013 Java Discovery.