Wednesday, August 31, 2005

SCJP study notes:Chapter 8 java.lang package

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 8 java.lang package

· Object class is the ultimate ancestor of all classes. If there is no extends clause, compiler inserts ‘extends object’. The following methods are defined in Object class. All methods are public, if not specified otherwise.

Method

Description

boolean equals(Object o)

just does a == comparison, override in descendents to provide meaningful comparison

final native void wait()

final native void notify()

final native void notifyAll()

Thread control. Two other versions of wait() accept timeout parameters and may throw InterruptedException.

native int hashcode()

Returns a hash code value for the object.

If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.

protected Object clone() throws CloneNotSupportedException

CloneNotSupportedException is a checked Exception

Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.

The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface. Also the method has to be made public to be called from outside the class.

Arrays have a public clone method.

int ia[ ][ ] = { { 1 , 2}, null };

int ja[ ][ ] = (int[ ] [ ])ia.clone();

A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, so ia and ja are different but ia[0] and ja[0] are same.

final native Class getClass()

Returns the runtime class of an object.

String toString

Returns the string representation of the object. Method in Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. Override to provide useful information.

protected void finalize() throws

Throwable

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

The finalize method in Object does nothing. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

· Math class is final, cannot be sub-classed.

· Math constructor is private, cannot be instantiated.

· All constants and methods are public and static, just access using class name.

· Two constants PI and E are specified.

· Methods that implement Trigonometry functions are native.

· All Math trig functions take angle input in radians.

Angle degrees * PI / 180 = Angle radians

· Order of floating/double values:

-Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive Numbers/Fractions --> Infinity

· abs – int, long, float, double versions available

· floor – greatest integer smaller than this number (look below towards the floor)

· ceil – smallest integer greater than this number (look above towards the ceiling)

· For floor and ceil functions, if the argument is NaN or infinity or positive zero or negative zero or already a value equal to a mathematical integer, the result is the same as the argument.

· For ceil, if the argument is less than zero but greater than –1.0, then the result is a negative zero

· random – returns a double between 0.0(including) and 1.0(excluding)

· round returns a long for double, returns an int for float. (closest int or long value to the argument)

The result is rounded to an integer by adding ½ , taking the floor of the result, and casting the result to type int / long.

(int)Math.floor(a + 0.5f)

(long)Math.floor(a + 0.5d)

· double rint(double) returns closest double equivalent to a mathematical integer. If two values are equal, it returns the even integer value. rint(2.7) is 3, rint(2.5) is 2.

· Math.min(-0.0, +0.0) returns –0.0, Math.max(-0.0, +0.0) returns 0.0, -0.0 == +0.0 returns true.

· For a NaN or a negative argument, sqrt returns a NaN.

· Every primitive type has a wrapper class (some names are different – Integer, Boolean, Character)

· Wrapper class objects are immutable.

· All Wrapper classes are final.

· All wrapper classes, except Character, have a constructor accepting string. A Boolean object, created by passing a string, will have a value of false for any input other than “true” (case doesn’t matter).

· Numeric wrapper constructors will throw a NumberFormatException, if the passed string is not a valid number. (empty strings and null strings also throw this exception)

· equals also tests the class of the object, so even if an Integer object and a Long object are having the same value, equals will return false.

· NaN’s can be tested successfully with equals method.

Float f1 = new Float(Float.NaN);

Float f2 = new Float(Float.NaN);

System.out.println( ""+ (f1 == f2)+" "+f1.equals(f2)+ " "+(Float.NaN == Float.NaN) );

The above code will print false true false.

· Numeric wrappers have 6 methods to return the numeric value – intValue(), longValue(), etc.

· valueOf method parses an input string (optionally accepts a radix in case of int and long) and returns a new instance of wrapper class, on which it was invoked. It’s a static method. For empty/invalid/null strings it throws a NumberFormatException. For null strings valueOf in Float and Double classes throw NullPointerException.

· parseInt and parseLong return primitive int and long values respectively, parsing a string (optionally a radix). Throw a NumberFormatException for invalid/empty/null strings.

· Numeric wrappers have overloaded toString methods, which accept corresponding primitive values (also a radix in case of int,long) and return a string.

· Void class represents void primitive type. It’s not instantiable. Just a placeholder class.

· Strings are immutable.

· They can be created from a literal, a byte array, a char array or a string buffer.

· Literals are taken from pool (for optimization), so == will return true, if two strings are pointing to the same literal.

· Anonymous String objects (literals) may have been optimized even across classes.

· A String created by new operator is always a different new object, even if it’s created from a literal.

· But a String can specify that its contents should be placed in a pool of unique strings for possible reuse, by calling intern() method. In programs that do a lot of String comparisons, ensuring that all Strings are in the pool, allows to use == comparison rather than the equals() method, which is slower.

· All string operations (concat, trim, replace, substring etc) construct and return new strings.

· toUpperCase and toLowerCase will return the same string if no case conversion was needed.

· equals takes an object (String class also has a version of equals that accepts a String), equalsIgnoreCase takes a string.

· Passing null to indexOf or lastIndexOf will throw NullPointerException, passing empty string returns 0, passing a string that’s not in the target string returns –1.

· trim method removes all leading and trailing white-space from a String and returns a new String. White-space means, all characters with value less than or equal to the space character – ‘\u0020’.

· String class is final.

· + and += operators are overloaded for Strings.

· reverse, append, insert are not String methods.

· String Buffers are mutable strings.

· StringBuffer is a final class.

· They can be created empty, from a string or with a capacity. An empty StringBuffer is created with 16-character capacity. A StringBuffer created from a String has the capacity of the length of String + 16. StringBuffers created with the specified capacity has the exact capacity specified. Since they can grow dynamically in size without bounds, capacity doesn’t have much effect.

· append, insert, setCharAt, reverse are used to manipulate the string buffer.

· setLength changes the length, if the current content is larger than specified length, it’s truncated. If it is smaller than the specified length, nulls are padded. This method doesn’t affect the capacity.

· equals on StringBuffer does a shallow comparison. (same like ==) Will return true only if the objects are same. Don’t use it to test content equality

· trim is not a StringBuffer method.

· There is no relationship between String and StringBuffer. Both extend Object class.

· String context means, ‘+’ operator appearing with one String operand. String concatenation cannot be applied to StringBuffers.

· A new String buffer is created.

· All operands are appended (by calling toString method, if needed)

· Finally a string is returned by calling toString on the String Buffer.

· String concatenation process will add a string with the value of “null”, if an object reference is null and that object is appearing in a concatenation expression by itself. But if we try to access its members or methods, a NullPointerException is thrown. The same is true for arrays, array name is replaced with null, but trying to index it when it’s null throws a NullPointerException.

SCJP study notes: Chapter 7 Threads

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 7 Threads

(Some info is outdated if you are preparing for the SCJP 1.4 exam).

· Java is fundamentally multi-threaded.

· Every thread corresponds to an instance of java.lang.Thread class or a sub-class.

· A thread becomes eligible to run, when its start() method is called. Thread scheduler co-ordinates between the threads and allows them to run.

· When a thread begins execution, the scheduler calls its run method.

Signature of run method – public void run()

· When a thread returns from its run method (or stop method is called – deprecated in 1.2), its dead. It cannot be restarted, but its methods can be called. (it’s just an object no more in a running state)

· If start is called again on a dead thread, IllegalThreadStateException is thrown.

· When a thread is in running state, it may move out of that state for various reasons. When it becomes eligible for execution again, thread scheduler allows it to run.

· There are two ways to implement threads.

1. Extend Thread class

· Create a new class, extending the Thread class.

· Provide a public void run method, otherwise empty run in Thread class will be executed.

· Create an instance of the new class.

· Call start method on the instance (don’t call run – it will be executed on the same thread)

2. Implement Runnable interface

· Create a new class implementing the Runnable interface.

· Provide a public void run method.

· Create an instance of this class.

· Create a Thread, passing the instance as a target – new Thread(object)

· Target should implement Runnable, Thread class implements it, so it can be a target itself.

· Call the start method on the Thread.

· JVM creates one user thread for running a program. This thread is called main thread. The main method of the class is called from the main thread. It dies when the main method ends. If other user threads have been spawned from the main thread, program keeps running even if main thread dies. Basically a program runs until all the user threads (non-daemon threads) are dead.

· A thread can be designated as a daemon thread by calling setDaemon(boolean) method. This method should be called before the thread is started, otherwise IllegalThreadStateException will be thrown.

· A thread spawned by a daemon thread is a daemon thread.

· Threads have priorities. Thread class have constants MAX_PRIORITY (10), MIN_PRIORITY (1), NORM_PRIORITY (5)

· A newly created thread gets its priority from the creating thread. Normally it’ll be NORM_PRIORITY.

· getPriority and setPriority are the methods to deal with priority of threads.

· Java leaves the implementation of thread scheduling to JVM developers. Two types of scheduling can be done.

1. Pre-emptive Scheduling.

Ways for a thread to leave running state -

· It can cease to be ready to execute ( by calling a blocking i/o method)

· It can get pre-empted by a high-priority thread, which becomes ready to execute.

· It can explicitly call a thread-scheduling method such as wait or suspend.

· Solaris JVM’s are pre-emptive.

· Windows JVM’s were pre-emptive until Java 1.0.2

2. Time-sliced or Round Robin Scheduling

· A thread is only allowed to execute for a certain amount of time. After that, it has to contend for the CPU (virtual CPU, JVM) time with other threads.

· This prevents a high-priority thread mono-policing the CPU.

· The drawback with this scheduling is – it creates a non-deterministic system – at any point in time, you cannot tell which thread is running and how long it may continue to run.

· Mactinosh JVM’s

· Windows JVM’s after Java 1.0.2

· Different states of a thread:

1. Yielding

· Yield is a static method. Operates on current thread.

· Moves the thread from running to ready state.

· If there are no threads in ready state, the yielded thread may continue execution, otherwise it may have to compete with the other threads to run.

· Run the threads that are doing time-consuming operations with a low priority and call yield periodically from those threads to avoid those threads locking up the CPU.

2. Sleeping

· Sleep is also a static method.

· Sleeps for a certain amount of time. (passing time without doing anything and w/o using CPU)

· Two overloaded versions – one with milliseconds, one with milliseconds and nanoseconds.

· Throws an InterruptedException.(must be caught)

· After the time expires, the sleeping thread goes to ready state. It may not execute immediately after the time expires. If there are other threads in ready state, it may have to compete with those threads to run. The correct statement is the sleeping thread would execute some time after the specified time period has elapsed.

· If interrupt method is invoked on a sleeping thread, the thread moves to ready state. The next time it begins running, it executes the InterruptedException handler.

3. Suspending

· Suspend and resume are instance methods and are deprecated in 1.2

· A thread that receives a suspend call, goes to suspended state and stays there until it receives a resume call on it.

· A thread can suspend it itself, or another thread can suspend it.

· But, a thread can be resumed only by another thread.

· Calling resume on a thread that is not suspended has no effect.

· Compiler won’t warn you if suspend and resume are successive statements, although the thread may not be able to be restarted.

4. Blocking

· Methods that are performing I/O have to wait for some occurrence in the outside world to happen before they can proceed. This behavior is blocking.

· If a method needs to wait an indeterminable amount of time until some I/O takes place, then the thread should graciously step out of the CPU. All Java I/O methods behave this way.

· A thread can also become blocked, if it failed to acquire the lock of a monitor.

5. Waiting

· wait, notify and notifyAll methods are not called on Thread, they’re called on Object. Because the object is the one which controls the threads in this case. It asks the threads to wait and then notifies when its state changes. It’s called a monitor.

· Wait puts an executing thread into waiting state.(to the monitor’s waiting pool)

· Notify moves one thread in the monitor’s waiting pool to ready state. We cannot control which thread is being notified. notifyAll is recommended.

· NotifyAll moves all threads in the monitor’s waiting pool to ready.

· These methods can only be called from synchronized code, or an IllegalMonitorStateException will be thrown. In other words, only the threads that obtained the object’s lock can call these methods.

Locks, Monitors and Synchronization

· Every object has a lock (for every synchronized code block). At any moment, this lock is controlled by at most one thread.

· A thread that wants to execute an object’s synchronized code must acquire the lock of the object. If it cannot acquire the lock, the thread goes into blocked state and comes to ready only when the object’s lock is available.

· When a thread, which owns a lock, finishes executing the synchronized code, it gives up the lock.

· Monitor (a.k.a Semaphore) is an object that can block and revive threads, an object that controls client threads. Asks the client threads to wait and notifies them when the time is right to continue, based on its state. In strict Java terminology, any object that has some synchronized code is a monitor.

· 2 ways to synchronize:

1. Synchronize the entire method

· Declare the method to be synchronized - very common practice.

· Thread should obtain the object’s lock.

2. Synchronize part of the method

· Have to pass an arbitrary object which lock is to be obtained to execute the synchronized code block (part of a method).

· We can specify “this” in place object, to obtain very brief locking – not very common.

· wait – points to remember

§ calling thread gives up CPU

§ calling thread gives up the lock

§ calling thread goes to monitor’s waiting pool

§ wait also has a version with timeout in milliseconds. Use this if you’re not sure when the current thread will get notified, this avoids the thread being stuck in wait state forever.

· notify – points to remember

§ one thread gets moved out of monitor’s waiting pool to ready state

§ notifyAll moves all the threads to ready state

§ Thread gets to execute must re-acquire the lock of the monitor before it can proceed.

· Note the differences between blocked and waiting.

Blocked

Waiting

Thread is waiting to get a lock on the monitor.

(or waiting for a blocking i/o method)

Thread has been asked to wait. (by means of wait method)

Caused by the thread tried to execute some synchronized code. (or a blocking i/o method)

The thread already acquired the lock and executed some synchronized code before coming across a wait call.

Can move to ready only when the lock is available. ( or the i/o operation is complete)

Can move to ready only when it gets notified (by means of notify or notifyAll)

· Points for complex models:

1. Always check monitor’s state in a while loop, rather than in an if statement.

2. Always call notifyAll, instead of notify.

· Class locks control the static methods.

· wait and sleep must be enclosed in a try/catch for InterruptedException.

· A single thread can obtain multiple locks on multiple objects (or on the same object)

· A thread owning the lock of an object can call other synchronous methods on the same object. (this is another lock) Other threads can’t do that. They should wait to get the lock.

· Non-synchronous methods can be called at any time by any thread.

· Synchronous methods are re-entrant. So they can be called recursively.

· Synchronized methods can be overrided to be non-synchronous. synchronized behavior affects only the original class.

· Locks on inner/outer objects are independent. Getting a lock on outer object doesn’t mean getting the lock on an inner object as well, that lock should be obtained separately.

· wait and notify should be called from synchronized code. This ensures that while calling these methods the thread always has the lock on the object. If you have wait/notify in non-synchronized code compiler won’t catch this. At runtime, if the thread doesn’t have the lock while calling these methods, an IllegalMonitorStateException is thrown.

· Deadlocks can occur easily. e.g, Thread A locked Object A and waiting to get a lock on Object B, but Thread B locked Object B and waiting to get a lock on Object A. They’ll be in this state forever.

· It’s the programmer’s responsibility to avoid the deadlock. Always get the locks in the same order.

· While ‘suspended’, the thread keeps the locks it obtained – so suspend is deprecated in 1.2

· Use of stop is also deprecated, instead use a flag in run method. Compiler won’t warn you, if you have statements after a call to stop, even though they are not reachable.

SCJP study notes: Chapter 6 Objects and Classes

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 6 Objects and Classes

Implementing OO relationships

· “is a” relationship is implemented by inheritance (extends keyword)

· “has a” relationship is implemented by providing the class with member variables.

Overloading and Overriding

· Overloading is an example of polymorphism. (operational / parametric)

· Overriding is an example of runtime polymorphism (inclusive)

· A method can have the same name as another method in the same class, provided it forms either a valid overload or override

Overloading

Overriding

Signature has to be different. Just a difference in return type is not enough.

Signature has to be the same. (including the return type)

Accessibility may vary freely.

Overriding methods cannot be more private than the overridden methods.

Exception list may vary freely.

Overriding methods may not throw more checked exceptions than the overridden methods.

Just the name is reused. Methods are independent methods. Resolved at compile-time based on method signature.

Related directly to sub-classing. Overrides the parent class method. Resolved at run-time based on type of the object.

Can call each other by providing appropriate argument list.

Overriding method can call overridden method by super.methodName(), this can be used only to access the immediate super-class’s method. super.super won’t work. Also, a class outside the inheritance hierarchy can’t use this technique.

Methods can be static or non-static. Since the methods are independent, it doesn’t matter. But if two methods have the same signature, declaring one as static and another as non-static does not provide a valid overload. It’s a compile time error.

static methods don’t participate in overriding, since they are resolved at compile time based on the type of reference variable. A static method in a sub-class can’t use ‘super’ (for the same reason that it can’t use ‘this’ for)

Remember that a static method can’t be overridden to be non-static and a non-static method can’t be overridden to be static. In other words, a static method and a non-static method cannot have the same name and signature (if signatures are different, it would have formed a valid overload)

There’s no limit on number of overloaded methods a class can have.

Each parent class method may be overridden at most once in any sub-class. (That is, you cannot have two identical methods in the same class)

· Variables can also be overridden, it’s known as shadowing or hiding. But, member variable references are resolved at compile-time. So at the runtime, if the class of the object referred by a parent class reference variable, is in fact a sub-class having a shadowing member variable, only the parent class variable is accessed, since it’s already resolved at compile time based on the reference variable type. Only methods are resolved at run-time.

public class Shadow {

public static void main(String s[]) {

S1 s1 = new S1();

S2 s2 = new S2();

System.out.println(s1.s); // prints S1

System.out.println(s1.getS()); // prints S1

System.out.println(s2.s); // prints S2

System.out.println(s2.getS()); // prints S2

s1 = s2;

System.out.println(s1.s); // prints S1, not S2 -

// since variable is resolved at compile time

System.out.println(s1.getS()); // prints S2 -

// since method is resolved at run time

}

}

class S1 {

public String s = "S1";

public String getS() {

return s;

}

}

class S2 extends S1{

public String s = "S2";

public String getS() {

return s;

}

}

In the above code, if we didn’t have the overriding getS() method in the sub-class and if we call the method from sub-class reference variable, the method will return only the super-class member variable value. For explanation, see the following point.

· Also, methods access variables only in context of the class of the object they belong to. If a sub-class method calls explicitly a super class method, the super class method always will access the super-class variable. Super class methods will not access the shadowing variables declared in subclasses because they don’t know about them. (When an object is created, instances of all its super-classes are also created.) But the method accessed will be again subject to dynamic lookup. It is always decided at runtime which implementation is called. (Only static methods are resolved at compile-time)

public class Shadow2 {

String s = "main";

public static void main(String s[]) {

S2 s2 = new S2();

s2.display(); // Produces an output – S1, S2

S1 s1 = new S1();

System.out.println(s1.getS()); // prints S1

System.out.println(s2.getS()); // prints S1 – since super-class method

// always accesses super-class variable

}

}

class S1 {

String s = "S1";

public String getS() {

return s;

}

void display() {

System.out.println(s);

}

}

class S2 extends S1{

String s = "S2";

void display() {

super.display(); // Prints S1

System.out.println(s); // prints S2

}

}

· With OO languages, the class of the object may not be known at compile-time (by virtue of inheritance). JVM from the start is designed to support OO. So, the JVM insures that the method called will be from the real class of the object (not with the variable type declared). This is accomplished by virtual method invocation (late binding). Compiler will form the argument list and produce one method invocation instruction – its job is over. The job of identifying and calling the proper target code is performed by JVM.

· JVM knows about the variable’s real type at any time since when it allocates memory for an object, it also marks the type with it. Objects always know ‘who they are’. This is the basis of instanceof operator.

· Sub-classes can use super keyword to access the shadowed variables in super-classes. This technique allows for accessing only the immediate super-class. super.super is not valid. But casting the ‘this’ reference to classes up above the hierarchy will do the trick. By this way, variables in super-classes above any level can be accessed from a sub-class, since variables are resolved at compile time, when we cast the ‘this’ reference to a super-super-class, the compiler binds the super-super-class variable. But this technique is not possible with methods since methods are resolved always at runtime, and the method gets called depends on the type of object, not the type of reference variable. So it is not at all possible to access a method in a super-super-class from a subclass.

public class ShadowTest {

public static void main(String s[]){

new STChild().demo();

}

}

class STGrandParent {

double wealth = 50000.00;

public double getWealth() {

System.out.println("GrandParent-" + wealth);

return wealth;

}

}

class STParent extends STGrandParent {

double wealth = 100000.00;

public double getWealth() {

System.out.println("Parent-" + wealth);

return wealth;

}

}

class STChild extends STParent {

double wealth = 200000.00;

public double getWealth() {

System.out.println("Child-" + wealth);

return wealth;

}

public void demo() {

getWealth(); // Calls Child method

super.getWealth(); // Calls Parent method

// Compiler error, GrandParent method cannot be accessed

//super.super.getWealth();

// Calls Child method, due to dynamic method lookup

((STParent)this).getWealth();

// Calls Child method, due to dynamic method lookup

((STGrandParent)this).getWealth();

System.out.println(wealth); // Prints Child wealth

System.out.println(super.wealth); // Prints Parent wealth

// Prints Parent wealth

System.out.println(((STParent)(this)).wealth);

// Prints GrandParent wealth

System.out.println(((STGrandParent)(this)).wealth);

}

}

· An inherited method, which was not abstract on the super-class, can be declared abstract in a sub-class (thereby making the sub-class abstract). There is no restriction. In the same token, a subclass can be declared abstract regardless of whether the super-class was abstract or not.

· Private members are not inherited, but they do exist in the sub-classes. Since the private methods are not inherited, they cannot be overridden. A method in a subclass with the same signature as a private method in the super-class is essentially a new method, independent from super-class, since the private method in the super-class is not visible in the sub-class.

public class PrivateTest {

public static void main(String s[]){

new PTSuper().hi(); // Prints always Super

new PTSub().hi(); // Prints Super when subclass doesn't have hi method

// Prints Sub when subclass has hi method

PTSuper sup;

sup = new PTSub();

sup.hi(); // Prints Super when subclass doesn't have hi method

// Prints Sub when subclass has hi method

}

}

class PTSuper {

public void hi() { // Super-class implementation always calls superclass hello

hello();

}

private void hello() { // This method is not inherited by subclasses, but exists in them.

// Commenting out both the methods in the subclass show this.

// The test will then print "hello-Super" for all three calls

// i.e. Always the super-class implementations are called

System.out.println("hello-Super");

}

}

class PTSub extends PTSuper {

public void hi() { // This method overrides super-class hi, calls subclass hello

try {

hello();

}

catch(Exception e) {}

}

void hello() throws Exception { // This method is independent from super-class hello

// Evident from, it's allowed to throw Exception

System.out.println("hello-Sub");

}

}

· Private methods are not overridden, so calls to private methods are resolved at compile time and not subject to dynamic method lookup. See the following example.

public class Poly {

public static void main(String args[]) {

PolyA ref1 = new PolyC();

PolyB ref2 = (PolyB)ref1;

System.out.println(ref2.g()); // This prints 1

// If f() is not private in PolyB, then prints 2

}

}

class PolyA {

private int f() { return 0; }

public int g() { return 3; }

}

class PolyB extends PolyA {

private int f() { return 1; }

public int g() { return f(); }

}

class PolyC extends PolyB {

public int f() { return 2; }

}

Constructors and Sub-classing

· Constructors are not inherited as normal methods, they have to be defined in the class itself.

· If you define no constructors at all, then the compiler provides a default constructor with no arguments. Even if, you define one constructor, this default is not provided.

· We can’t compile a sub-class if the immediate super-class doesn’t have a no argument default constructor, and sub-class constructors are not calling super or this explicitly (and expect the compiler to insert an implicit super() call )

· A constructor can call other overloaded constructors by ‘this (arguments)’. If you use this, it must be the first statement in the constructor. This construct can be used only from within a constructor.

· A constructor can’t call the same constructor from within. Compiler will say ‘ recursive constructor invocation’

· A constructor can call the parent class constructor explicitly by using ‘super (arguments)’. If you do this, it must be first the statement in the constructor. This construct can be used only from within a constructor.

· Obviously, we can’t use both this and super in the same constructor. If compiler sees a this or super, it won’t insert a default call to super().

· Constructors can’t have a return type. A method with a class name, but with a return type is not considered a constructor, but just a method by compiler. Expect trick questions using this.

· Constructor body can have an empty return statement. Though void cannot be specified with the constructor signature, empty return statement is acceptable.

· Only modifiers that a constructor can have are the accessibility modifiers.

· Constructors cannot be overridden, since they are not inherited.

· Initializers are used in initialization of objects and classes and to define constants in interfaces. These initializers are :

1. Static and Instance variable initializer expressions.

Literals and method calls to initialize variables. Static variables can be initialized

only by static method calls.

Cannot pass on the checked exceptions. Must catch and handle them.

2. Static initializer blocks.

Used to initialize static variables and load native libraries.

Cannot pass on the checked exceptions. Must catch and handle them.

3. Instance initializer blocks.

Used to factor out code that is common to all the constructors.

Also useful with anonymous classes since they cannot have constructors.

All constructors must declare the uncaught checked exceptions, if any.

Instance Initializers in anonymous classes can throw any exception.

· In all the initializers, forward referencing of variables is not allowed. Forward referencing of methods is allowed.

· Order of code execution (when creating an object) is a bit tricky.

1. static variables initialization.

2. static initializer block execution. (in the order of declaration, if multiple blocks found)

3. constructor header ( super or this – implicit or explicit )

4. instance variables initialization / instance initializer block(s) execution

5. rest of the code in the constructor

Interfaces

· All methods in an interface are implicitly public, abstract, and never static.

· All variables in an interface are implicitly static, public, final. They cannot be transient or volatile. A class can shadow the variables it inherits from an interface, with its own variables.

· A top-level interface itself cannot be declared as static or final since it doesn’t make sense.

· Declaring parameters to be final is at method’s discretion, this is not part of method signature.

· Same case with final, synchronized, native. Classes can declare the methods to be final, synchronized or native whereas in an interface they cannot be specified like that. (These are implementation details, interface need not worry about this)

· But classes cannot implement an interface method with a static method.

· If an interface specifies an exception list for a method, then the class implementing the interface need not declare the method with the exception list. (Overriding methods can specify sub-set of overridden method’s exceptions, here none is a sub-set). But if the interface didn’t specify any exception list for a method, then the class cannot throw any exceptions.

· All interface methods should have public accessibility when implemented in class.

· Interfaces cannot be declared final, since they are implicitly abstract.

· A class can implement two interfaces that have a method with the same signature or variables with the same name.

Inner Classes

· A class can be declared in any scope. Classes defined inside of other classes are known as nested classes. There are four categories of nested classes.

1. Top-level nested classes / interfaces

· Declared as a class member with static modifier.

· Just like other static features of a class. Can be accessed / instantiated without an instance of the outer class. Can access only static members of outer class. Can’t access instance variables or methods.

· Very much like any-other package level class / interface. Provide an extension to packaging by the modified naming scheme at the top level.

· Classes can declare both static and non-static members.

· Any accessibility modifier can be specified.

· Interfaces are implicitly static (static modifier also can be specified). They can have any accessibility modifier. There are no non-static inner, local or anonymous interfaces.

2. Non-static inner classes

· Declared as a class member without static.

· An instance of a non-static inner class can exist only with an instance of its enclosing class. So it always has to be created within a context of an outer instance.

· Just like other non-static features of a class. Can access all the features (even private) of the enclosing outer class. Have an implicit reference to the enclosing instance.

· Cannot have any static members.

· Can have any access modifier.

3. Local classes

· Defined inside a block (could be a method, a constructor, a local block, a static initializer or an instance initializer). Cannot be specified with static modifier.

· Cannot have any access modifier (since they are effectively local to the block)

· Cannot declare any static members.(Even declared in a static context)

· Can access all the features of the enclosing class (because they are defined inside the method of the class) but can access only final variables defined inside the method (including method arguments). This is because the class can outlive the method, but the method local variables will go out of scope – in case of final variables, compiler makes a copy of those variables to be used by the class. (New meaning for final)

· Since the names of local classes are not visible outside the local context, references of these classes cannot be declared outside. So their functionality could be accessed only via super-class references (either interfaces or classes). Objects of those class types are created inside methods and returned as super-class type references to the outside world. This is the reason that they can only access final variables within the local block. That way, the value of the variable can be always made available to the objects returned from the local context to outside world.

· Cannot be specified with static modifier. But if they are declared inside a static context such as a static method or a static initializer, they become static classes. They can only access static members of the enclosing class and local final variables. But this doesn’t mean they cannot access any non-static features inherited from super classes. These features are their own, obtained via the inheritance hierarchy. They can be accessed normally with ‘this’ or ‘super’.

4. Anonymous classes

· Anonymous classes are defined where they are constructed. They can be created wherever a reference expression can be used.

· Anonymous classes cannot have explicit constructors. Instance initializers can be used to achieve the functionality of a constructor.

· Typically used for creating objects on the fly.

· Anonymous classes can implement an interface (implicit extension of Object) or explicitly extend a class. Cannot do both.

Syntax: new interface name() { } or new class name() { }

· Keywords implements and extends are not used in anonymous classes.

· Abstract classes can be specified in the creation of an anonymous class. The new class is a concrete class, which automatically extends the abstract class.

· Discussion for local classes on static/non-static context, accessing enclosing variables, and declaring static variables also holds good for anonymous classes. In other words, anonymous classes cannot be specified with static, but based on the context, they could become static classes. In any case, anonymous classes are not allowed to declare static members. Based on the context, non-static/static features of outer classes are available to anonymous classes. Local final variables are always available to them.

· One enclosing class can have multiple instances of inner classes.

· Inner classes can have synchronous methods. But calling those methods obtains the lock for inner object only not the outer object. If you need to synchronize an inner class method based on outer object, outer object lock must be obtained explicitly. Locks on inner object and outer object are independent.

· Nested classes can extend any class or can implement any interface. No restrictions.

· All nested classes (except anonymous classes) can be abstract or final.

· Classes can be nested to any depth. Top-level static classes can be nested only within other static top-level classes or interfaces. Deeply nested classes also have access to all variables of the outer-most enclosing class (as well the immediate enclosing class’s)

· Member inner classes can be forward referenced. Local inner classes cannot be.

· An inner class variable can shadow an outer class variable. In this case, an outer class variable can be referred as (outerclassname.this.variablename).

· Outer class variables are accessible within the inner class, but they are not inherited. They don’t become members of the inner class. This is different from inheritance. (Outer class cannot be referred using ‘super’, and outer class variables cannot be accessed using ‘this’)

· An inner class variable can shadow an outer class variable. If the inner class is sub-classed within the same outer class, the variable has to be qualified explicitly in the sub-class. To fully qualify the variable, use classname.this.variablename. If we don’t correctly qualify the variable, a compiler error will occur. (Note that this does not happen in multiple levels of inheritance where an upper-most super-class’s variable is silently shadowed by the most recent super-class variable or in multiple levels of nested inner classes where an inner-most class’s variable silently shadows an outer-most class’s variable. Problem comes only when these two hierarchy chains (inheritance and containment) clash.)

· If the inner class is sub-classed outside of the outer class (only possible with top-level nested classes) explicit qualification is not needed (it becomes regular class inheritance)

// Example 1

public class InnerInnerTest {

public static void main(String s[]) {

new Outer().new Inner().new InnerInner().new InnerInnerInner().doSomething();

new Outer().new InnerChild().doSomething();

new Outer2().new Inner2().new InnerInner2().doSomething();

new InnerChild2().doSomething();

}

}

class Outer {

String name = "Vel";

class Inner {

String name = "Sharmi";

class InnerInner {

class InnerInnerInner {

public void doSomething() {

// No problem in accessing without full qualification,

// inner-most class variable shadows the outer-most class variable

System.out.println(name); // Prints "Sharmi"

System.out.println(Outer.this.name); // Prints "Vel", explicit reference to Outer

// error, variable is not inherited from the outer class, it can be just accessible

// System.out.println(this.name);

// System.out.println(InnerInner.this.name);

// System.out.println(InnerInnerInner.this.name);

// error, super cannot be used to access outer class.

// super will always refer the parent, in this case Object

// System.out.println(super.name);

System.out.println(Inner.this.name); // Prints "Sharmi", Inner has declared 'name'

}

}

}

}

/* This is an inner class extending an inner class in the same scope */

class InnerChild extends Inner {

public void doSomething() {

// compiler error, explicit qualifier needed

// 'name' is inherited from Inner, Outer's 'name' is also in scope

// System.out.println(name);

System.out.println(Outer.this.name); // prints "Vel", explicit reference to Outer

System.out.println(super.name); // prints "Sharmi", Inner has declared 'name'

System.out.println(this.name); // prints "Sharmi", name is inherited by InnerChild

}

}

}

class Outer2 {

static String name = "Vel";

static class Inner2 {

static String name = "Sharmi";

class InnerInner2 {

public void doSomething() {

System.out.println(name); // prints "Sharmi", inner-most hides outer-most

System.out.println(Outer2.name); // prints "Vel", explicit reference to Outer2's static variable

// System.out.println(this.name); // error, 'name' is not inherited

// System.out.println(super.name); // error, super refers to Object

}

}

}

}

/* This is a stand-alone class extending an inner class */

class InnerChild2 extends Outer2.Inner2 {

public void doSomething() {

System.out.println(name); // prints "Sharmi", Inner2's name is inherited

System.out.println(Outer2.name); // prints "Vel", explicit reference to Outer2's static variable

System.out.println(super.name); // prints "Sharmi", Inner2 has declared 'name'

System.out.println(this.name); // prints "Sharmi", name is inherited by InnerChild2

}

}

// Example 2

public class InnerTest2 {

public static void main(String s[]) {

new OuterClass().doSomething(10, 20);

// This is legal

// OuterClass.InnerClass ic = new OuterClass().new InnerClass();

// ic.doSomething();

// Compiler error, local inner classes cannot be accessed from outside

// OuterClass.LocalInnerClass lic = new OuterClass().new LocalInnerClass();

// lic.doSomething();

new OuterClass().doAnonymous();

}

}

class OuterClass {

final int a = 100;

private String secret = "Nothing serious";

public void doSomething(int arg, final int fa) {

final int x = 100;

int y = 200;

System.out.println(this.getClass() + " - in doSomething");

System.out.print("a = " + a + " secret = " + secret + " arg = " + arg + " fa = " + fa);

System.out.println(" x = " + x + " y = " + y);

// Compiler error, forward reference of local inner class

// new LocalInnerClass().doSomething();

abstract class AncestorLocalInnerClass { } // inner class can be abstract

final class LocalInnerClass extends AncestorLocalInnerClass { // can be final

public void doSomething() {

System.out.println(this.getClass() + " - in doSomething");

System.out.print("a = " + a );

System.out.print(" secret = " + secret);

// System.out.print(" arg = " + arg); // Compiler error, accessing non-final argument

System.out.print(" fa = " + fa);

System.out.println(" x = " + x);

// System.out.println(" y = " + y); // Compiler error, accessing non-final variable

}

}

new InnerClass().doSomething(); // forward reference fine for member inner class

new LocalInnerClass().doSomething();

}

abstract class AncestorInnerClass { }

interface InnerInterface { final int someConstant = 999;} // inner interface

class InnerClass extends AncestorInnerClass implements InnerInterface {

public void doSomething() {

System.out.println(this.getClass() + " - in doSomething");

System.out.println("a = " + a + " secret = " + secret + " someConstant = " + someConstant);

}

}

public void doAnonymous() {

// Anonymous class implementing the inner interface

System.out.println((new InnerInterface() { }).someConstant);

// Anonymous class extending the inner class

( new InnerClass() {

public void doSomething() {

secret = "secret is changed";

super.doSomething();

}

} ).doSomething();

}

}

Entity

Declaration Context

Accessibility Modifiers

Outer instance

Direct Access to enclosing context

Defines static or non-static members

Package level class

As package member

Public or default

No

N/A

Both static and non-static

Top level nested class (static)

As static class member

All

No

Static members in enclosing context

Both static and non-static

Non static inner class

As non-static class member

All

Yes

All members in enclosing context

Only non-static

Local class (non-static)

In block with non-static context

None

Yes

All members in enclosing context + local final variables

Only non-static

Local class (static)

In block with static context

None

No

Static members in enclosing context + local final variables

Only non-static

Anonymous class (non-static)

In block with non-static context

None

Yes

All members in enclosing context + local final variables

Only non-static

Anonymous class (static)

In block with static context

None

No

Static members in enclosing context + local final variables

Only non-static

Package level interface

As package member

Public or default

No

N/A

Static variables and non-static method prototypes

Top level nested interface (static)

As static class member

All

No

Static members in enclosing context

Static variables and non-static method prototypes