Friday, August 8, 2008

Nested Classes and Interfaces

A class that is declared within another class or interface, is called a nested class. Similarly, an interface that is declared within another class or interface, is called a nested interface. A top-level class or a top-level interface is one that is not nested.

In addition to the top-level classes and interfaces, there are four categories of nested classes and one of nested interfaces, defined by the context these classes and interfaces are declared in:

static member classes and interfaces

non-static member classes

local classes

anonymous classes

The last three categories are collectively known as inner classes. They differ from non-inner classes in one important aspect: that an instance of an inner class may be associated with an instance of the enclosing class. The instance of the enclosing class is called the immediately enclosing instance. An instance of an inner class can access the members of its immediately enclosing instance by their simple name.

A static member class or interface is defined as a static member in a class or an interface. Such a nested class can be instantiated like any ordinary top-level class, using its full name. No enclosing instance is required to instantiate a static member class. Note that there are no non-static member, local, or anonymous interfaces. Interfaces are always defined either at the top level or as static members.

Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.

Local classes can be defined in the context of a block as in a method body or a local block, just as local variables can be defined in a method body or a local block.

Anonymous classes can be defined as expressions and instantiated on the fly. An instance of a local (or an anonymous) class has an enclosing instance associated with it, if the local (or anonymous) class is declared in a non-static context.

A nested class or interface cannot have the same name as any of its enclosing classes or interfaces.

Table 7.1 presents a summary of various aspects relating to nested classes and interfaces. The Entity column lists the different kinds of classes and interfaces that can be declared. The Declaration Context column lists the lexical context in which the class or interface can be defined. The Accessibility Modifiers column indicates what accessibility can be specified for the class or interface. The Enclosing Instance column specifies whether an enclosing instance is associated with an instance of the class. The Direct Access to Enclosing Context column lists what is directly accessible in the enclosing context from within the class or interface. The Declarations in Entity Body column refers to what can be declared in the class or interface body. Subsequent sections on each nested class elaborate on the summary presented in Table 7.1. (N/A in the table means not applicable.)

Nested type (i.e., nested classes and interfaces) can be regarded as a form of encapsulation, enforcing relationships between types by greater proximity. They allow structuring of types and a special binding relationship between a nested object and its enclosing instance. Used judiciously, they can be beneficial, but unrestrained use of nested classes can easily result in unreadable code.

Nested type (i.e., nested classes and interfaces) can be regarded as a form of encapsulation, enforcing relationships between types by greater proximity. They allow structuring of types and a special binding relationship between a nested object and its enclosing instance. Used judiciously, they can be beneficial, but unrestrained use of nested classes can easily result in unreadable code.

Table 7.1. Overview of Classes and Interfaces

Entity

Declaration Context

Accessibility Modifiers

Enclosing Instance

Direct Access to Enclosing Context

Declarations in Entity Body

Top-level Class (or Interface)

Package

public or default

No

N/A

All that are valid in a class (or interface) body

Static Member Class (or Interface)

As static member of enclosing class or interface

All

No

Static members in enclosing context

All that are valid in a class (or interface) body

Non-static Member Class

As non-static member of enclosing class or interface

All

Yes

All members in enclosing context

Only non-static declarations + final static fields

Local Class

In block with non-static context

None

Yes

All members in enclosing context + final local variables

Only non-static declarations + final static fields

In block with static context

None

No

Static members in enclosing context + final local variables

Only non-static declarations + final static fields

Anonymous Class

As expression in non-static context

None

Yes

All members in enclosing context + final local variables

Only non-static declarations + final static fields

As expression in static context

None

No

Static members in enclosing context + final local variables

Only non-static declarations + final static fields


Wednesday, August 6, 2008

Object Class

The Object Class
All classes extend the Object class, either directly or indirectly. A class declaration, without the extends clause, implicitly extends the Object class. Thus, the Object class is always at the top of any inheritance hierarchy. The Object class defines the basic functionality that all objects exhibit and that all classes inherit. Note that this also applies for arrays, since these are genuine objects in Java.

The Object class provides the following general utility methods :

int hashCode()

When storing objects in hash tables, this method can be used to get a hash value for an object. This value is guaranteed to be consistent during the execution of the program.

boolean equals(Object obj)

Object reference and value equality are discussed together with the == and != operators (see Section 3.10, p. 68). The equals() method in the Object class returns true only if the two references compared denote the same object. The equals() method is usually overridden to provide the semantics of object value equality, as is the case for the wrapper classes and the String class.

final Class getClass()

Returns the runtime class of the object, which is represented by an object of the class java.lang.Class at runtime.

protected Object clone() throws CloneNotSupportedException

New objects that are exactly the same (i.e., have identical states) as the current object can be created by using the clone() method, that is, primitive values and reference values are copied. This is called shallow copying. A class can override this method to provide its own notion of cloning. For example, cloning a composite object by recursively cloning the constituent objects is called deep copying.

When overridden, the method in the subclass is usually declared public to allow any client to clone objects of the class.

If the overriding clone() method relies on the clone() method in the Object class, then the subclass must implement the Cloneable marker interface to indicate that its objects can be safely cloned. Otherwise, the clone() method in the Object class will throw a checked CloneNotSupportedException.

String toString()

If a subclass does not override this method, it returns a textual representation of the object, which has the following format:

"(name of the class)@(hash code value of object)"

This method is usually overridden and used for debugging purposes. The method call System.out.println(objRef) will implicitly convert its argument to a textual representation using the toString() method.

protected void finalize() throws Throwable

This method is called on an object just before it is garbage collected, so that any cleaning up can be done. However, the default finalize() method in the Object class does not do anything useful.

In addition, the Object class provides support for thread communication in synchronized code, through the following methods :

final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
final void notify()
final void notifyAll()

A thread invokes these method on the object whose lock it holds. A thread waits for notification by another thread.

Tuesday, August 5, 2008

Do u know Java well! Try these questions.. already asked in MNC's interviews

Question: What is the package?
Answer: The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

Question: What is native code?
Answer: The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

Question: Is Java code slower than native code?
Answer: Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

Question: What is the serialization?
Answer: The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

Question: How to make a class or a bean serializable?
Answer: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable

Question: How many methods in the Serializable interface?
Answer:There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

Question: . How many methods in the Externalizable interface?
Answer: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

Question: What is the difference between Serializalble and Externalizable interface?
Answer: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

Question: What is a transient variable?
Answer: A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

Question: Which containers use a border layout as their default layout?
Answer: The Window, Frame and Dialog classes use a border layout as their default layout.

Question: . How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Question: What is synchronization and why is it important?
Answer: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

Question: What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Question: How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Question: What is synchronization and why is it important?
Answer: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

Question: What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Question: What are three ways in which a thread can enter the waiting state?
Answer: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.