Anonymous Inner Classes

When a local inner class seems too much for your needs, you can declare anonymous classes that extend a class or implement an interface. These classes are defined at the same time they are instantiated with new. For example, consider the walkThrough method. The class Iter is fairly lightweight and is not needed outside the method. The name Iter doesn't add much value to the codewhat is important is that it is an Iterator object. The walkThrough method could use an anonymous inner class instead:

public static Iterator
walkThrough(final Object[] objs)
{

return new Iterator()
{
private int pos = 0;
public boolean hasNext()
{
return (pos <>
}
public Object next() throws NoSuchElementException
{
if (pos >= objs.length)
throw new NoSuchElementException();
return objs[pos++];
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}



Anonymous classes are defined in the new expression itself, as part of a statement. The type specified to new is the supertype of the anonymous class. Because Iterator is an interface, the anonymous class in walkThrough implicitly extends Object and implements Iterator. An anonymous class cannot have an explicit extends or implements clause, nor can it have any modifiers, including annotations.

Anonymous inner classes cannot have explicit constructors declared because they have no name to give the constructor. If an anonymous inner class is complex enough that it needs explicit constructors then it should probably be a local inner class. In practice, many anonymous inner classes need little or no initialization. In either case, an anonymous inner class can have initializers and initialization blocks that can access the values that would logically have been passed as a constructor argument. The only construction problem that remains is the need to invoke an explicit superclass constructor.
Attr constructor and overrides setValue to print out the new value each time it is changed:

Attr name = new Attr("Name")
{
public Object setValue(Object nv)
{
System.out.println("Name set to " + nv);
return super.setValue(nv);
}
};



In the Iterator example we invoked the no-arg superclass constructor for Objectthe only constructor that can ever be used when an anonymous inner class has an interface type.

Anonymous classes are simple and direct but can easily become very hard to read. The further they nest, the harder they are to understand. The nesting of the anonymous class code that will execute in the future inside the method code that is executing now adds to the potential for confusion. You should probably avoid anonymous classes that are longer than about six lines, and you should use them in only the simplest of expressions. We stretch this rule in the walkThrough example because the sole purpose of the method is to return that object, but when a method does more, anonymous classes must be kept quite small or the code becomes illegible. When anonymous classes are used properly, they are a good tool for keeping simple classes simple. When misused, they create impenetrable inscrutability.


Local Inner Classes

You can define inner classes in code blocks, such as a method body, constructor, or initialization block. These local inner classes are not members of the class of which the code is a part but are local to that block, just as a local variable is. Such classes are completely inaccessible outside the block in which they are definedthere is simply no way to refer to them. But instances of such classes are normal objects that can be passed as arguments and returned from methods, and they exist until they are no longer referenced. Because local inner classes are inaccessible, they can't have access modifiers, nor can they be declared static because, well, they are local inner classes. All of the other class modifiers, including annotations, can be applied, though only strictfp and annotations have practical applications.

A local inner class can access all the variables that are in scope where the class is definedlocal variables, method parameters, instance variables (assuming it is a non-static block), and static variables. The only restriction is that a local variable or method parameter can be accessed only if it is declared final.
Consider the standard interface Iterator defined in the java.util package. This interface defines a way to iterate through a group of objects. It is commonly used to provide access to the elements in a container object but can be used for any general-purpose iteration:

package java.util;

public interface Iterator
{
boolean hasNext();
E next() throws NoSuchElementException;
void remove() throws UnsupportedOperationException,
IllegalStateException;
}



The hasNext method returns true if next has more elements to return. The remove method removes from the collection the last element returned by next. But remove is optional, which means an implementation is allowed to throw UnsupportedOperationException. If remove is invoked before next, or is invoked multiple times after a single call to next, then IllegalStateException is thrown. NoSuchElementExceptionalso part of the java.util packageis thrown if next is invoked when there are no more elements.
Here is a simple method that returns an Iterator to walk through an array of Object instances:

public static Iterator
walkThrough(final Object[] objs)
{

class Iter implements Iterator
{
private int pos = 0;
public boolean hasNext()
{
return (pos <>
}
public Object next() throws NoSuchElementException
{
if (pos >= objs.length)
throw new NoSuchElementException();
return objs[pos++];
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
return new Iter();
}



The Iter class is local to the walkThrough method; it is not a member of the enclosing class. Because Iter is local to the method, it has access to all the final variables of the methodin particular the parameter objs. It defines a pos field to keep track of where it is in the objs array. (This code assumes that Iterator and NoSuchElementException are imported from java.util in the source that contains walkThrough.)

Inner Classes in Static Contexts
We stated that an inner class is usually associated with an instance of the enclosing class. It is possible to declare a local inner class, or an anonymous inner class (see next section), in a static context: within a static method, a static initialization block, or as part of a static initializer. In these static contexts there is no corresponding instance of the enclosing class, and so the inner class instance has no enclosing class instance. In these circumstances, any attempt to use a qualified-this expression to refer to an enclosing class's instance fields or methods will result in a compile-time error.

Accessing Enclosing Objects

The toString method of Action directly uses the number field of its enclosing BankAccount object. A nested class can access all members of its enclosing classincluding private fields and methodswithout qualification because it is part of the enclosing class's implementation. An inner class can simply name the members of its enclosing object to use them. The names in the enclosing class are all said to be in scope. The enclosing class can also access the private members of the inner class, but only by an explicit reference to an inner class object such as lastAct. While an object of the inner class is always associated with an object of the enclosing class, the converse is not true. An object of the enclosing class need not have any inner class objects associated with it, or it could have many.

When deposit creates an Action object, a reference to the enclosing BankAccount object is automatically stored in the new Action object. Using this saved reference, the Action object can always refer to the enclosing BankAccount object's number field by the simple name number, as shown in toString. The name of the reference to the enclosing object is this preceded by the enclosing class namea form known as qualified-this. For example, toString could reference the number field of the enclosing BankAccount object explicitly:

return BankAccount.this.number + ": " + act + " " + amount;



The qualified-this reference reinforces the idea that the enclosing object and the inner object are tightly bound as part of the same implementation of the enclosing class. This is further reinforced by the qualified-super reference, which allows access to members of the enclosing instance's superclass that have been hidden, or overridden, by the enclosing class. For example, given a class T that extends S, within T we can invoke the superclass implementation of a method m, by using super.m() in an expression. Similarly, in an inner class of T, we can invoke the same implementation of m using T.super.m() in an expressiona qualified-super referenceand similarly for fields of S hidden by fields in T.

A nested class can have its own nested classes and interfaces. References to enclosing objects can be obtained for any level of nesting in the same way: the name of the class and this. If class X encloses class Y which encloses class Z, code in Z can explicitly access fields of X by using X.this.

The language does not prevent you from deeply nesting classes, but good taste should. A doubly nested class such as Z has three name scopes: itself, its immediate enclosing class Y, and outermost class X. Someone reading the code for Z must understand each class thoroughly to know in which context an identifier is bound and which enclosing object was bound to which nested object. We recommend nesting only one level under most circumstances. Nesting more than two levels invites a readability disaster and should probably never be attempted.

Inner Classes

Non-static nested classes are called inner classes. Non-static class members are associated with instances of a classnon-static fields are instance variables and non-static methods operate on an instance. Similarly, an inner class is also (usually) associated with an instance of a class, or more specifically an instance of an inner class is associated with an instance of its enclosing classthe enclosing instance or enclosing object.

You often need to closely tie a nested class object to a particular object of the enclosing class. Consider, for example, a method for the BankAccount class that lets you see the last action performed on the account, such as a deposit or withdrawal:

public class BankAccount
{
private long number; // account number
private long balance; // current balance (in cents)
private Action lastAct; // last action performed

public class Action
{
private String act;
private long amount;
Action(String act, long amount)
{
this.act = act;
this.amount = amount;
}
public String toString()
{
// identify our enclosing account
return number + ": " + act + " " + amount;
}
}

public void deposit(long amount)
{
balance += amount;
lastAct = new Action("deposit", amount);
}

public void withdraw(long amount)
{
balance -= amount;
lastAct = new Action("withdraw", amount);
}
// ...
}



The class Action records a single action on the account. It is not declared static, and that means its objects exist relative to an object of the enclosing class.

The relationship between an Action object and its BankAccount object is established when the Action object is created, as shown in the deposit and withdraw methods. When an inner class object is created, it must be associated with an object of its enclosing class. Usually, inner class objects are created inside instance methods of the enclosing class, as in deposit and withdraw. When that occurs the current object this is associated with the inner object by default. The creation code in deposit is the same as the more explicit

lastAct = this.new Action("deposit", amount);



Any BankAccount object could be substituted for this. For example, suppose we add a transfer operation that takes a specified amount from one account and places it in the current accountsuch an action needs to update the lastAct field of both account objects:

public void transfer(BankAccount other, long amount)
{

other.withdraw(amount);
deposit(amount);
lastAct = this.new Action("transfer", amount);
other.lastAct = other.new Action("transfer", amount);
}



In this case we bind the second Action object to the otherBankAccount object and store it as the last action of the other account. Each BankAccount object should only refer to Action objects for which that BankAccount object is the enclosing instance. It would make no sense above, for example, to store the same Action object in both the current lastAct field and other.lastAct.

An inner class declaration is just like a top-level class declaration except for one restrictioninner classes cannot have static members (including static nested types), except for final static fields that are initialized to constants or expressions built up from constants. The rationale for allowing constants to be declared in an inner class is the same as that for allowing them in interfacesit can be convenient to define constants within the type that uses them.


Nested Classes and Interfaces

Static Nested Types

A nested class or interface that is declared as a static member of its enclosing class or interface acts just like any non-nested, or top-level, class or interface, except that its name and accessibility are defined by its enclosing type. The name of a nested type is expressed as EnclosingName.NestedName. The nested type is accessible only if the enclosing type is accessible.

Static nested types serve as a structuring and scoping mechanism for logically related types. However, static nested types are members of their enclosing type and as such can access all other members of the enclosing type including private onesthrough an appropriate object reference of course. This gives the nested type a special, privileged relationship with the enclosing type.

Because static nested types are members of their enclosing type, the same accessibility rules apply to them as for other members. For classes this means that a static nested class or interface can have private, package, protected, or public access, while for interfaces, nested types are implicitly public.

Static Nested Classes
The static nested class is the simplest form of nested class. You declare one by preceding the class declaration with the static modifier. When nested in an interface, a class declaration is always static and the modifier is, by convention, omitted. A static nested class acts just like any top-level class. It can extend any other class (including the class it is a member of), implement any interface and itself be used for further extension by any class to which it is accessible. It can be declared final or abstract, just as a top-level class can, and it can have annotations applied to it.

public class BankAccount
{

private long number; // account number
private long balance; // current balance (in cents)

public static class Permissions {
public boolean canDeposit,
canWithdraw,
canClose;
}
// ...
}

The Permissions class is defined inside the BankAccount class, making it a member of that class. When permissionsFor returns a Permissions object, it can refer to the class simply as Permissions in the same way it can refer to balance without qualification: Permissions is a member of the class. The full name of the class is BankAccount.Permissions. This full name clearly indicates that the class exists as part of the BankAccount class, not as a stand-alone type. Code outside the BankAccount class must use the full name, for example:

BankAccount.Permissions perm = acct.permissionsFor(owner);



If BankAccount were in a package named bank, the full name of the class would be bank.BankAccount.Permissions

Static nested classes are members of their enclosing type. Static nested classes enclosed in an interface are implicitly public; if enclosed by a class, you can declare them to be accessible in any way you like. You can, for example, declare a class that is an implementation detail to be private. We declare Permissions to be public because programmers using BankAccount need to use the class.

Since Permissions is a member of BankAccount, the Permissions class can access all other members of BankAccount, including all inherited members. For example, if Permissions declared a method that took a BankAccount object as an argument, that method would be able to directly access both the number and balance fields of that account. In this sense the nested class is seen as part of the implementation of the enclosing class and so is completely trusted.

There is no restriction on how a static nested class can be extendedit can be extended by any class to which it is accessible. Of course, the extended class does not inherit the privileged access that the nested class has to the enclosing class.


Nested Interfaces

Nested interfaces are also always static and again, by convention the static modifier is omitted from the interface declaration. They serve simply as a structuring mechanism for related types. When we look at non-static nested classes you will see that they are inherently concerned with implementation issues. Since interfaces do not dictate implementation they cannot be non-static.

When to Use Interfaces?

An interface defines a type with an abstract contract. An abstract class also defines a type with an abstract contract. Which should you use and when?

There are two major differences between interfaces and abstract classes:

  1. Interfaces provide a form of multiple inheritance, because you can implement multiple interfaces. A class can extend only one other class, even if that class has only abstract methods.

  2. An abstract class can have a partial implementation, protected parts, static methods, and so on, whereas interfaces are limited to public constants and public methods with no implementation.

These differences usually direct the choice of which tool is best to use in a particular implementation. If multiple inheritance is important or even useful, interfaces are used. However, an abstract class enables you to provide some or all of the implementation so that it can be inherited easily, rather than by explicit forwarding.

Any major class you expect to be extended, whether abstract or not, should be an implementation of an interface. Although this approach requires a little more work on your part, it enables a whole category of use that is otherwise precluded. For example, suppose we had created an Attributed class instead of an Attributed interface with an AttributedImpl implementation class. In that case, programmers who wanted to create new classes that extended other existing classes could never use Attributed, since you can extend only one classthe class AttributedBody could never have been created. Because Attributed is an interface, programmers have a choice: They can extend AttributedImpl directly and avoid the forwarding, or, if they cannot extend, they can at least use composition and forwarding to implement the interface. And if the general implementation provided is incorrect, they can write their own implementation. You can even provide multiple possible implementations of the interface to prospective users. Whatever implementation strategy programmers prefer, the objects they create are Attributed.

Inheriting, Overriding, and Overloading Methods

A subinterface inherits all the methods declared in its superinterfaces. If a declared method in a subinterface has the same signature (name and parameter list) as an inherited method and the same, or covariant, return type, then the new declaration overrides any and all existing declarations. Overriding in interfaces, unlike overriding in classes, has no semantic effectthe interface effectively contains multiple declarations of the same method, but in any one implementing class there can only be one implementation of that method.

Similarly, if an interface inherits more than one method with the same signature, or if a class implements different interfaces containing a method with the same signature, there is only one such method. The implementation of this method is ultimately defined by the class implementing the interfaces, and there is no ambiguity there. If the methods have the same signature but different return types, then one of the return types must be a subtype of all the others, otherwise a compile-time error occurs. The implementation must define a method that returns that common subtype.

The real issue is whether a single implementation of the method can honor all the contracts implied by that method being part of the different interfaces. This may be an impossible requirement to satisfy in some circumstances. For example:

interface CardDealer
{

void draw(); // flip top card
void deal(); // distribute cards
void shuffle();
}
interface GraphicalComponent
{

void draw(); // render on default device
void draw(Device d); // render on 'd'
void rotate(int degrees);
void fill(Color c);
}

interface GraphicalCardDealer
CardDealer, GraphicalComponent { }



Here it is difficult to write an implementation of draw() that can satisfy the two different contracts independently. If you try to satisfy them simultaneously, you are unlikely to achieve the desired results: flipping a card each time the screen gets repainted.

As with overriding in class extension, the overriding method is not permitted to throw more checked exceptions than the method it overrides. If two or more method declarations are inherited, without overriding, and differ in the exceptions they throw, then the implementation of that method must satisfy all the throws clauses of those declarations. Again the main issue is whether such distinct methods can have a single implementation that honors all contracts.



Working with Interfaces
The first decision to make is whether having attributes is reflected in the type of the object. An object could, if you chose, contain a set of attributes and allow programmers access to that set. Or you could say that being able to store attributes on an object is a part of its type and so should be part of the type hierarchy. Both positions are legitimate. We believe that representing the ability to hold attributes in the type hierarchy is most useful. We will create an Attributed type to be used for objects that can be attributed by attaching Attr objects to them.

To create an Attributed type you could define a class that would form the superclass for all attributed objects. But then programmers must decide whether to inherit from Attributed or from some other useful class. Instead we make Attributed into an interface:

public interface Attributed
{

void add(Attr newAttr);
Attr find(String attrName);
Attr remove(String attrName);
java.util.Iterator attrs();
}



This interface declares four methods: one for adding a new attribute to an Attributed object; one for finding whether an attribute of a given name has been added to that object; one for removing an attribute from an object; and one for accessing all of the attributes currently attached to the object.

When we add an attribute to an object, that object considers itself the owner of that Attr instance until it is removed. If the attribute has its value changed or is shared among a number of objects, then the expectation is that the programmer makes such changes and performs such sharing in a manner that makes sense to the application. If the programmer is not to be trusted in this, then methods should specify that they make defensive copies of parameters, and/or return values, such that no harmful changes can occur.


Implementing Interfaces
Interfaces describe contracts in a pure, abstract form, but an interface is interesting only if a class implements it.

Some interfaces are purely abstractthey do not have any useful general implementation but must be implemented afresh for each new class. Most interfaces, however, may have several useful implementations. In the case of our Attributed interface, we can imagine several possible implementations that use various strategies to store a set of attributes.

One strategy might be simple and fast when only a few attributes are in a set; another one might be optimized for attribute sets that are queried more often than they are changed; yet another design might be optimized for sets that change frequently. If there were a package of various implementations for the Attributed interface, a class might choose to implement the Attributed interface through any one of them or through its own implementation.

First, here is the AttributedImpl class:

import java.util.*;

class AttributedImpl implements Attributed, Iterable
{

protected Map attrTable =
new HashMap();

public void add(Attr newAttr)
{

attrTable.put(newAttr.getName(), newAttr);
}

public Attr find(String name)
{

return attrTable.get(name);
}

public Attr remove(String name)
{

return attrTable.remove(name);
}

public Iterator attrs()
{

return attrTable.values().iterator();
}

public Iterator iterator()
{

return attrs();
}
}



The initializer for attrTable creates a HashMap object to hold attributes. This HashMap object does most of the actual work. The HashMap class uses the key object's hashCode method to hash any object it is given as a key. No explicit hash method is needed since String already provides a good hashCode implementation.

When a new attribute is added, the Attr object is stored in the hash map under its name, and then you can easily use the hash map to find and remove attributes by name. The attrs method returns the Iterator for the hash map's values, giving access to all the attributes of the current object.

We chose to make this implementation of Attributed also implement Iterable, as the attributes are the only things an AttributedImpl contains. To do this, we had to define the iterator method to return the same value as the attrs method.

Using an Implementation
You can use an implementing class like AttributedImpl by simply extending the class. This is the simplest tool when it is available because all the methods and their implementations are inherited. But if you need to support more than one interface or extend a different class, you must use a different approach. The most common approach is to create an object of an implementing class and forward all the methods of the interface to that object, returning any valuesthis is often called composition.

In composition and forwarding, each method in the class that is inherited from the interface invokes the implementation from another object and returns the result. Here is an implementation of the Attributed interface that uses an AttributedImpl object to build an attributed version of our previously defined celestial body class Body:

import java.util.Iterator;

class AttributedBody extends Body
implements Attributed
{
private AttributedImpl attrImpl = new AttributedImpl();

public AttributedBody() {
super();
}

public AttributedBody(String name, Body orbits) {
super(name, orbits);
}

// Forward all Attributed methods to the attrImpl object

public void add(Attr newAttr)
{ attrImpl.add(newAttr); }
public Attr find(String name)
{ return attrImpl.find(name); }
public Attr remove(String name)
{ return attrImpl.remove(name); }
public Iterator attrs()
{ return attrImpl.attrs(); }
}


The declaration that AttributedBody extends Body and implements Attributed defines the contract of AttributedBody. The implementations of all Body's methods are inherited from the Body class itself. Each method of Attributed is implemented by forwarding the invocation to the AttributedImpl object's equivalent method, returning its value (if any). This also means that you must add a field of type AttributedImpl to use in the forwarding methods and initialize that field to refer to an AttributedImpl object.


Interface Declarations

An interface is declared using the keyword interface, giving the interface a name and listing the interface members between curly braces.

An interface can declare three kinds of members:

>constants (fields)
>methods
>nested classes and interfaces

All interface members are implicitly public, but, by convention, the public modifier is omitted. Having non-public members in an interface would make little sense; where it does make sense you can use the accessibility of the interface itself to control access to the interface members.

Interface Constants
An interface can declare named constants. These constants are defined as fields but are implicitly public, static, and finalagain, by convention, the modifiers are omitted from the field declarations.
Because interfaces contain no implementation details, they cannot define normal fieldssuch a definition would be dictating implementation policy to the classes that choose to implement the interface. Interfaces can define named constants because these are useful in the design of types. For example, an interface that had differing levels of verbosity in its contract might have the following:

interface Verbose
{

int SILENT = 0;
int TERSE = 1;
int NORMAL = 2;
int VERBOSE = 3;

void setVerbosity(int level);
int getVerbosity();
}



SILENT, TERSE, NORMAL, and VERBOSE can be passed to the setVerbosity method, giving names to constant values that represent specific meanings.


Interface Methods
The methods declared in an interface are implicitly abstract because no implementation is, or can be, given for them. For this reason the method body is simply a semicolon after the method header. By convention, the abstract modifier on the method declaration is omitted.


Extending Interfaces
Interfaces can be extended using the extends keyword. Interfaces, unlike classes, can extend more than one other interface:

public interface SerializableRunnable
extends java.io.Serializable, Runnable
{
// ...
}



The SerializableRunnable interface extends both java.io.Serializable and Runnable, which means that all methods and constants defined by those interfaces are now part of the SerializableRunnable contract, together with any new methods and constants it defines. The interfaces that are extended are the superinterfaces of the new interface and the new interface is a subinterface of its superinterfaces.

Because interfaces support multiple inheritance, the inheritance graph can contain multiple paths to the same superinterface. This means that constants and methods can be accessed in different ways. However, because interfaces define no implementation of methods, and provide no per-object fields, there are no issues regarding the semantics of this form of multiple inheritance.

In the subinterface and in any object implementing the subinterface, any reference to the constant using its simple name will refer to the constant defined in the subinterface. The inherited constant can still be accessed with the qualified name of the constant, that is, the interface name followed by dot and then the constant namethe usual way of referring to static members.

interface X
{

int val = 1;
}
interface Y extends X
{

int val = 2;
int sum = val + X.val;
}



Interface Y has two constants: val and sum. From inside Y, to refer to the hidden val in its superinterface you must qualify it as X.val. Externally, you can access the constants of Y by using the normal static forms of Y.val and Y.sum, and of course you can access X's val constant by using X.val.

These rules are, of course, identical to those concerning the inheritance of static fields in classes.

When a class implements Y you can access the constants in Y as though they were constants declared in the class. For example, given

class Z implements Y { }



you can do

System.out.println("Z.val=" + Z.val + ", Z.sum=" + Z.sum);



but there is no way to refer to X.val via Z. However, given an instance of Z you can use an explicit cast to access X.val:

Z z = new Z();
System.out.println("z.val=" + z.val +
", ((Y)z).val=" + ((Y)z).val +
", ((X)z).val=" + ((X)z).val);



which prints out

z.val=2, ((Y)z).val=2, ((X)z).val=1



as you would expect. Again these are the same rules that apply to static fields in extended classesit doesn't matter whether a class inherits a static field from a superclass or a superinterface.

While all these rules are necessary from a language perspective, they have little practical consequencethere are few reasons to hide existing fields, and all accesses to static fields, whether class or interface, should be via the name of the type in which that field is declared.

If an interface inherits two or more constants with the same name, then any simple reference to the constant is ambiguous and results in a compile-time error. For example, given the previous interface declarations and the following:

interface C
{

String val = "Interface C";
}
interface D extends X, C { }



then the expression D.val is ambiguousdoes it mean the integer val or the String reference val? Inside D you would have to explicitly use X.val or C.val.

A class that implements more than one interface, or that extends a class and implements one or more interfaces, can experience the same hiding and ambiguity issues as an interface that extends more than one interface. The class's own static fields can hide the inherited fields of the interfaces it implements or the class it extends, and simple references to multiply-inherited non-hidden fields will be ambiguous.


Fibonacci numbers In Java

import java.io.*;
import java.math.BigInteger;

public class BigFib
{
BigInteger last;
BigInteger next;
int n;

public BigFib () {
n = 0;
last = new BigInteger("0");
next = new BigInteger("1");
}


public BigInteger getFib(int c, PrintStream printTo)
{
BigInteger tmp;
for( ; c > 0; c -= 2)
{
last = last.add(next); n++;
if (printTo != null) printTo.println(" " + n + "\t" + last);
next = next.add(last); n++;
if (printTo != null) printTo.println(" " + n + "\t" + next);
}
if (c == 0) return next;
else return last;
}


public static final int defaultLimit = 100;


public static void main(String args[])
{
BigInteger answer;

BigFib fib = new BigFib();

System.out.println("\t\t Fibonacci sequence!");
System.out.println("");

System.out.println();
int limit = 100;
if (args.length > 0)
{
try { limit = Integer.parseInt(args[0]); }
catch (NumberFormatException nfe)
{
System.err.println("Bad number, using default " + limit);
}
if (limit < 1)
{
limit = defaultLimit;
System.err.println("Limit too low, using default " + limit);
}
}

answer = fib.getFib(limit, System.out);
}
}

Collection classifier

import java.util.*;

public class CollectionClassifier2
{
public static String classify(Collection c)
{
return (c instanceof Set ? "Set" :
(c instanceof List ? "List" : "Unknown Collection"));
}

public static void main(String[] args)
{
Collection[] tests = new Collection[]
{
new HashSet(), // A Set
new ArrayList(), // A List
new HashMap().values() // Neither Set nor List
};

for (int i = 0; i < tests.length; i++)
System.out.println(classify(tests[i]));
}
}

Cloning an Object

class MyClass implements Cloneable {
public MyClass() {
}
public Object clone() {
Cloneable theClone = new MyClass();
// Initialize theClone.
return theClone;
}
}

//Here's some code to create a clone.

MyClass myObject = new MyClass();
MyClass myObjectClone = (MyClass)myObject.clone();

//Arrays are automatically cloneable:
int[] ints = new int[]{123, 234};
int[] intsClone = (int[])ints.clone();

Simple Class

class Body
{
public long idNum;
public String name;
public Body orbits;

public static long nextID = 0;
}

A class is declared using the keyword class, giving the class a name and listing the class members between curly braces. A class declaration creates a type name, so references to objects of that type can be declared with a simple

Body mercury;
This declaration states that mercury is a variable that can hold a reference to an object of type Body. The declaration does not create an objectit declares only a reference that is allowed to refer to a Body object. During its existence, the reference mercury may refer to any number of Body objects. These objects must be explicitly created. In this respect, the Java programming language is different from languages in which objects are created when you declare variables.

Class Members

A class can have three kinds of members:

  • Fields are the data variables associated with a class and its objects and hold the state of the class or object.

  • Methods contain the executable code of a class and define the behavior of objects.

  • Nested classes and nested interfaces are declarations of classes or interfaces that occur nested within the declaration of another class or interface.


Classes and Objects

The fundamental programming unit of the Java programming language is the class. Classes provide the structure for objects and the mechanisms to manufacture objects from a class definition. Classes define methods: collections of executable code that are the focus of computation and that manipulate the data stored in objects. Methods provide the behavior of the objects of a class. Although you can compute using only primitive typesinteger, floating-point, and so onalmost any interesting program will create and manipulate objects.

Object-oriented programming strictly separates the notion of what is to be done from how it is done. "What" is described as a set of methods (and sometimes publicly available data) and their associated semantics. This combinationmethods, data, and semanticsis often described as a contract between the designer of the class and the programmer who uses it because it says what happens when certain methods are invoked on an object. This contract defines a type such that all objects that are instances of that type are known to honor that contract.

Exception Handlers

What do you do when an error occurs in a program? In many languages, error conditions are signaled by unusual return values like 1. Programmers often don't check for exceptional values because they may assume that errors "can't happen." On the other hand, adding error detection and recovery to what should be a straightforward flow of logic can complicate that logic to the point where the normal flow is completely obscured. An ostensibly simple task such as reading a file into memory might require about seven lines of code. Error checking and reporting expands this to 40 or more lines. Making normal operation the needle in your code haystack is undesirable.

Checked exceptions manage error handling. Checked exceptions force you to consider what to do with errors where they may occur in the code. If a checked exception is not handled, this is noticed at compile time, not at run time when problems have been compounded because of the unchecked error.

A method that detects an unusual error condition throws an exception. Exceptions can be caught by code farther back on the calling stackthis invoking code can handle the exception as needed and then continue executing. Uncaught exceptions result in the termination of the thread of execution, but before it terminates the thread's UncaughtExceptionHandler is given the opportunity to respond to the exception as best it canperhaps doing nothing more than reporting that the exception occurred.

An exception is an object, with type, methods, and data. Representing exceptions as objects is useful, because an exception object can include data, methods, or both to report on or recover from specific kinds of exceptions. Exception objects are generally derived from the Exception class, which provides a string field to describe the error. All exceptions must be subclasses of the class Throwable, which is the superclass of Exception.

The paradigm for using exceptions is the trycatchfinally sequence: you try something; if that something throws an exception, you catch the exception; and finally you clean up from either the normal code path or the exception code path, whichever actually happened.

Here is a getdataSet method that returns a set of data read from a file. If the file for the data set cannot be found or if any other I/O exception occurs, this method throws an exception describing the error. First, we define a new exception type BadDataSetException to describe such an error. Then we declare that the method getdataSet tHRows that exception using a throws clause in the method header:

class BadDataSetException extends Exception { }

class MyUtilities {
public double[] getDataSet(String setName)
throws BadDataSetException
{
String file = setName + ".dset";
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readDataSet(in);
} catch (IOException e) {
throw new BadDataSetException();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
; // ignore: we either read the data OK
// or we're throwing BadDataSetException
}
}
}
// ... definition of readDataSet ...
}



First we turn the data set name into a file name. Then we try to open the file and read the data using the method readDataSet. If all goes well, readDataSet will return an array of doubles, which we will return to the invoking code. If opening or reading the file causes an I/O exception, the catch clause is executed. The catch clause creates a new BadDataSetException object and throws it, in effect translating the I/O exception into an exception specific to getdataSet. Methods that invoke geTDataSet can catch the new exception and react to it appropriately. In either casereturning successfully with the data set or catching and then throwing an exceptionthe code in the finally clause is executed to close the file if it was opened successfully. If an exception occurs during close, we catch it but ignore itthe semicolon by itself forms an empty statement, which does nothing. Ignoring exceptions is not a good idea in general, but in this case it occurs either after the data set is successfully readin which case the method has fulfilled its contractor the method is already in the process of throwing an exception. If a problem with the file persists, it will be reported as an exception the next time we try to use it and can be more appropriately dealt with at that time.

You will use finally clauses for cleanup code that must always be executed. You can even have a try-finally statement with no catch clauses to ensure that cleanup code will be executed even if uncaught exceptions are thrown.

If a method's execution can result in checked exceptions being thrown, it must declare the types of these exceptions in a throws clause, as shown for the getdataSet method. A method can throw only those checked exceptions it declaresthis is why they are called checked exceptions. It may throw those exceptions directly with tHRow or indirectly by invoking a method that throws exceptions. Exceptions of type RuntimeException, Error, or subclasses of these exception types are unchecked exceptions and can be thrown anywhere, without being declared.

Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some waysuch as the IOException that may occur reading a file. Declaring the checked exceptions that a method throws allows the compiler to ensure that the method throws only those checked exceptions it declared and no others. This check prevents errors in cases in which your method should handle another method's exceptions but does not. In addition, the method that invokes your method is assured that your method will not result in unexpected checked exceptions.

Unchecked exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time. For example, the ArrayIndexOutOfBoundsException thrown when you access outside the bounds of an array tells you that your program calculated an index incorrectly, or failed to verify a value to be used as an index. These are errors that should be corrected in the program code. Given that you can make errors writing any statement it would be totally impractical to have to declare or catch all the exceptions that could arise from those errorshence they are unchecked.

Interfaces

Sometimes you want only to declare methods an object must support but not to supply the implementation of those methods. As long as their behavior meets specific criteriacalled the contractimplementation details of the methods are irrelevant. These declarations define a type, and any class that implements those methods can be said to have that type, regardless of how the methods are implemented. For example, to ask whether a particular value is contained in a set of values, details of how those values are stored are irrelevant. You want the methods to work equally well with a linked list of values, a hashtable of values, or any other data structure.

To support this, you can define an interface. An interface is like a class but has only empty declarations of its methods. The designer of the interface declares the methods that must be supported by classes that implement the interface and declares what those methods should do. Here is a Lookup interface for finding a value in a set of values:

interface Lookup
{
/** Return the value associated with the name, or
* null if there is no such value */
Object find(String name);
}



The Lookup interface declares one method, find, that takes a String and returns the value associated with that name, or null if there is no associated value. In the interface no implementation can be given for the methoda class that implements the interface is responsible for providing a specific implementationso instead of a method body we simply have a semicolon. Code that uses references of type Lookup (references to objects that implement the Lookup interface) can invoke the find method and get the expected results, no matter what the actual type of the object is:

void processValues(String[] names, Lookup table)
{
for (int i = 0; i <>
{
Object value = table.find(names[i]);
if (value != null)
processValue(names[i], value);
}
}



A class can implement as many interfaces as you choose. This example implements Lookup using a simple array (methods to set or remove values are left out for simplicity):

class SimpleLookup implements Lookup
{
private String[] names;
private Object[] values;

public Object find(String name)
{
for (int i = 0; i <>
{
if (names[i].equals(name))
return values[i];
}
return null; // not found
}

// ...
}



An interface can also declare named constants that are static and final. Additionally, an interface can declare other nested interfaces and even classes. These nested types are discussed in detail in Chapter 5. All the members of an interface are implicitly, or explicitly, publicso they can be accessed anywhere the interface itself is accessible.

Interfaces can be extended using the extends keyword. An interface can extend one or more other interfaces, adding new constants or new methods that must be implemented by any class that implements the extended interface.

A class's supertypes are the class it extends and the interfaces it implements, including all the supertypes of those classes and interfaces. So an object is not only an instance of its particular class but also of any of its supertypes, including interfaces. An object can be used polymorphically with both its superclass and any superinterfaces, including any of their supertypes.

A class's subtypes are the classes that extend it, including all of their subtypes. An interface's subtypes are the interfaces that extend it, and the classes that implement it, including all of their subtypes.


Extending a Class

One of the major benefits of object orientation is the ability to extend, or subclass, the behavior of an existing class and continue to use code written for the original class when acting on an instance of the subclass. The original class is known as the superclass. When you extend a class to create a new class, the new extended class inherits fields and methods of the superclass.

If the subclass does not specifically override the behavior of the superclass, the subclass inherits all the behavior of its superclass because it inherits the fields and methods of its superclass. In addition, the subclass can add new fields and methods and so add new behavior.

Consider the Walkman example. The original model had a single jack for one person to listen to the tape. Later models incorporated two jacks so two people could listen to the same tape. In the object-oriented world, the two-jack model extends, or is a subclass of, the basic one-jack model. The two-jack model inherits the characteristics and behavior of the basic model and adds new behavior of its own.

Customers told Sony they wanted to talk to each other while sharing a tape in the two-jack model. Sony enhanced the two-jack model to include two-way communications so people could chat while listening to music. The two-way communications model is a subclass of the two-jack model, inherits all its behavior, and again adds new behavior.

Sony created many other Walkman models. Later models extend the capabilities of the basic modelthey subclass the basic model and inherit features and behavior from it.

Let's look at an example of extending a class. Here we extend our former PointPixel class requires a color in addition to x and y coordinates: class to represent a pixel that might be shown on a screen. The new

class Pixel extends Point 
{
Color color;

public void clear()
{
super.clear();
color = null;
}

}

Pixel extends both the data and behavior of its Point superclass. Pixel extends the data by adding a field named color. Pixel also extends the behavior of PointPoint's clear method. by overriding

Pixel objects can be used by any code designed to work with Point objects. If a method expects a parameter of type Point, you can hand it a Pixel object and it just works. All the Point code can be used by anyone with a Pixel in hand. This feature is known as polymorphisma single object like Pixel can have many ( poly-) forms (-morph) and can be used as both a Pixel object and a Point object.

Pixel's behavior extends Point's behavior. Extended behavior can be entirely new (adding color in this example) or can be a restriction on old behavior that follows all the original requirements. An example of restricted behavior might be PixelScreen object, restricting x and y to the dimensions of the screen. If the original Point class did not forbid restrictions for coordinates, a class with restricted range would not violate the original class's behavior. objects that live inside some kind of

An extended class often overrides the behavior of its superclass by providing new implementations of one or more of the inherited methods. To do this the extended class defines a method with the same signature and return type as a method in the superclass. In the Pixel example, we override clear to obtain the proper behavior that Pixel requires. The clear that Pixel inherited from PointPoint's fields but obviously can't know about the new color field declared in the Pixel subclass. knows only about

Invoking Methods of the Superclass

To make Pixel do the correct "clear" behavior, we provide a new implementation of clear that first invokes its superclass's clear using the super reference. The super reference is a lot like the this reference described previously except that super references things from the superclass, whereas this references things from the current object.

The invocation super.clear() looks to the superclass to execute clear as it would for an object of the superclassnamely, Point. After invoking super.clear() to clear out the Point part of the object, we add new functionality to set color to a reasonable empty value. We choose null, a reference to no object.

What would happen had we not invoked super.clear() in the previous example? Pixel's clearcolor to its null value, but the x and y variables that Pixel inherited from Point would not be set to any "cleared" values. Not clearing all the values of a Pixel object, including its Point parts, is probably a bug. method would set

When you invoke super.method (), the runtime system looks back up the inheritance hierarchy to the first superclass that contains the required method . If Point didn't have a clear method, for example, the runtime system would look at Point's superclass for such a method and invoke that, and so on.

For all other references, invoking a method uses the actual class of the object, not the type of the object reference. Here is an example:

Point point = new Pixel();
point.clear(); // uses Pixel's clear()
In this example, Pixel's version of clear is invoked even though the variable that holds the Pixel is declared as a Point reference. But if we invoke super.clear() inside one of Pixel's methods, that invocation will use the Point class's implementation of the clear method.

The Object Class

Classes that do not explicitly extend any other class implicitly extend the Object class. All objects are polymorphically of class Object, so Object is the general-purpose type for references that can refer to objects of any class:

Object oref = new Pixel();
oref = "Some String";

In this example, oref is correctly assigned references to Pixel and String objects even though those classes have no relationship except that both have Object as a superclass.

Type Casting

The following code fragment seems quite reasonable (if not particularly useful) but results in a compile-time error:

String name = "Petronius";
Object obj = name;
name = obj; // INVALID: won't compile

We declare and initialize a String reference which we then assign to a general-purpose ObjectString back to the String reference. Why doesn't this work? The problem is that while a String is always an Object, an Object is not necessarily a String, and even though you can see that in this case it really is a String, the compiler is not so clever. To help the compiler you have to tell it that the object referred to by obj is actually a String and so can be assigned to name: reference, and then we try to assign the reference to a

name = (String) obj;    // That's Good
Telling the compiler that the type of an expression is really a different type is known as type casting or type conversion. You perform a type cast by prefixing the expression with the new type in parentheses. The compiler doesn't automatically trust you when you do this and so it checks that you are telling the truth. A smart compiler may be able to tell at compile time that you are telling the truth; otherwise, it will insert a run time check to verify that the cast really is allowed. If you lie to the compiler and the run time check fails, the runtime system reports this by throwing a ClassCastException. As the Java programming language is strongly typed there are strict rules concerning assignments between types.

what is String Objects?

A String class type deals specifically with sequences of character data and provides language-level support for initializing them. The String class provides a variety of methods to operate on String objects.

You've already seen string literals in examples like the HelloWorld program. When you write a statement such as

System.out.println("Hello, world");



the compiler actually creates a String object initialized to the value of the specified string literal and passes that String object as the argument to the println method.

You don't need to specify the length of a String object when you create it. You can create a new String object and initialize it all in one statement, as shown in this example:

class StringsDemo
{
public static void main(String[] args)
{
String myName = "Petronius";

myName = myName + " Arbiter";
System.out.println("Name = " + myName);
}
}



Here we declare a String variable called myName and initialize it with an object reference to a string literal. Following initialization, we use the String concatenation operator (+) to make a new String object with new contents and store a reference to this new string object into the variable. Finally, we print the value of myName on the standard output stream. The output when you run this program is

Name = Petronius Arbiter



The concatenation operator can also be used in the short-hand += form, to assign the concatenation of the original string and the given string, back to the original string reference. Here's an upgraded program:

class BetterStringsDemo
{
public static void main(String[] args)
{
String myName = "Petronius";
String occupation = "Reorganization Specialist";

myName += " Arbiter";

myName += " ";
myName += "(" + occupation + ")";
System.out.println("Name = " + myName);
}
}



Now when you run the program, you get this output:

Name = Petronius Arbiter (Reorganization Specialist)



String objects have a length method that returns the number of characters in the string. Characters are indexed from 0 tHRough length()-1, and can be accessed with the charAt method, which takes an integer index and returns the character at that index. In this regard a string is similar to an array of characters, but String objects are not arrays of characters and you cannot assign an array of characters to a String reference. You can, however, construct a new String object from an array of characters by passing the array as an argument to a String constructor. You can also obtain an array of characters with the same contents as a string using the toCharArray method.

String objects are read-only, or immutable: The contents of a String never change. When you see statements like

str = "redwood";
// ... do something with str ..
str = "oak";

the second assignment gives a new value to the variable str, which is an object reference to a different string object with the contents "oak". Every time you perform operations that seem to modify a String object, such as the += operation in BetterStringsDemo, you actually get a new read-only String object, while the original String object remains unchanged.


The concatenation operator converts primitive values to strings using the toString method of the corresponding wrapper class. This conversion doesn't give you any control over the format of the resulting string. Formatted conversion can be done with the java.util.Formatter class. A Formatter can write its output to a string, a file, or some other output device. For convenience the System.out.printf method (for "print formatted") uses a formatter to write to System.out. Formatted output uses a format string together with a set of values to format. The format string contains normal text together with format specifiers that tell the formatter how you want the subsequent values to be formatted. For example, you can print the value of Math.PI to three decimal places using

System.out.printf("The value of Math.PI is %.3f %n", Math.PI);

which prints

The value of Math.PI is 3.142

whereas using println and string concatenation you'd get:

The value of Math.PI is 3.141592653589793

A format specifier consists of at least two parts: it starts with a % character, and it ends with a conversion indicator. The conversion identifies both the type of the value to format, and the basic form. For example, %f says to format a floating-point value in the usual decimal form, as used for Math.PI above, whereas %e says to format a floating point value in scientific notationfor example, 3.142e+00. Integer values can be formatted by %d for normal decimal, or %x for hexadecimal form. A string can be formatted by %s.

A format specifier can provide additional formatting information. You can provide a width that indicates the minimum number of characters to printuseful for aligning columns of data. If the formatted value has fewer characters than the width, it is padded with spaces to fit the minimum size. This lets you align values easily. Some conversions also allow a precision value to be given, which is written as . followed by a non-negative number. For floating-point values using %f the precision indicates how many decimal places to round toin the example above the value of Math.PI is rounded to 3 decimal places because of the .3 in the format specifier. If both a width and precision are given they are written in the form width.precision. Additional flags in the format specifier can, among other things, request zero padding (instead of spaces) or left-justification (the default is right justification).


Arrays In JAVA

Simple variables that hold one value are useful but are not sufficient for many applications. A program that plays a game of cards would want a number of Card objects it could manipulate as a whole. To meet this need, you use arrays.

An array is a collection of variables all of the same type. The components of an array are accessed by simple integer indexes. In a card game, a Deck object might look like this:

public class Deck
{
public static final int DECK_SIZE = 52;
private Card[] cards = new Card[DECK_SIZE];
public void print() {
for (int i = 0; i < cards.length; i++)
System.out.println(cards[i]);
}
// ...
}

First we declare a constant called DECK_SIZE to define the number of cards in a deck. This constant is public so that anyone can find out how many cards are in a deck. Next we declare a cards field for referring to all the cards. This field is declared private, which means that only the methods in the current class can access itthis prevents anyone from manipulating our cards directly. The modifiers public and private are access modifiers because they control who can access a class, interface, field, or method.

We declare the cards field as an array of type Card by following the type name in the declaration with square brackets [ and ]. We initialize cards to a new array with DECK_SIZE variables of type Card. Each Card element in the array is implicitly initialized to null. An array's length is fixed when it is created and can never change.

The println method invocation shows how array components are accessed. It encloses the index of the desired element within square brackets following the array name.

You can probably tell from reading the code that array objects have a length field that says how many elements the array contains. The bounds of an array are integers between 0 and length-1, inclusive. It is a common programming error, especially when looping through array elements, to try to access elements that are outside the bounds of the array. To catch this sort of error, all array accesses are bounds checked, to ensure that the index is in bounds. If you try to use an index that is out of bounds, the runtime system reports this by throwing an exception in your programan ArrayIndexOutOfBoundsException.

An array with length zero is an empty array. Methods that take arrays as arguments may require that the array they receive is non-empty and so will need to check the length. However, before you can check the length of an array you need to ensure that the array reference is not null. If either of these checks fail, the method may report the problem by throwing an IllegalArgumentException.

For example, here is a method that averages the values in an integer array:

static double average(int[] values)
{
if (values == null)
throw new IllegalArgumentException();
else
if (values.length == 0)
throw new IllegalArgumentException();
else {
double sum = 0.0;
for (int i = 0; i < values.length; i++)
sum += values[i];



return sum / values.length;
}

}

This code works but the logic of the method is almost completely lost in the nested ifelse statements ensuring the array is non-empty. To avoid the need for two if statements, we could try to test whether the argument is null or whether it has a zero length, by using the boolean inclusive-OR operator (|):

if (values == null | values.length == 0)
throw new IllegalArgumentException();

Unfortunately, this code is not correct. Even if values is null, this code will still attempt to access its length field because the normal boolean operators always evaluate both operands. This situation is so common when performing logical operations that special operators are defined to solve it. The conditional boolean operators evaluate their right-hand operand only if the value of the expression has not already been determined by the left-hand operand. We can correct the example code by using the conditional-OR (||) operator:

if (values == null || values.length == 0)
throw new IllegalArgumentException();

Now if values is null the value of the conditional-OR expression is known to be true and so no attempt is made to access the length field.

The binary boolean operatorsAND (&), inclusive-OR (|), and exclusive-OR (^)are logical operators when their operands are boolean values and bitwise operators when their operands are integer values. The conditional-OR (||) and conditional-AND (&&) operators are logical operators and can only be used with boolean operands.

Methods and Parameters

Objects of the previously defined Point class are exposed to manipulation by any code that has a reference to a Point object, because its fields are declared public. The Point class is an example of the simplest kind of class. Indeed, some classes are this simple. They are designed to fit purely internal needs for a package (a group of cooperating classes) or to provide simple data containers when those are all you need.

The real benefits of object orientation, however, come from hiding the implementation of a class behind operations performed on its data. Operations of a class are declared via its methodsinstructions that operate on an object's data to obtain results. Methods access internal implementation details that are otherwise hidden from other objects. Hiding data behind methods so that it is inaccessible to other objects is the fundamental basis of data encapsulation.

If we enhance the Point class with a simple clear method
(to clear, or reset the coordinates to zero), it might look like this:

public void clear()
{
x = 0.0;
y = 0.0;
}



The clear method has no parameters, hence the empty () pair after its name; clear is declared void because it does not return any value. Inside a method, fields and other methods of the class can be named directlywe can simply say x and y without an explicit object reference.

Invoking a Method
Objects in general do not operate directly on the data of other objects, although, as you saw in the Point class, a class can make its fields publicly accessible. Well-designed classes usually hide their data so that it can be changed only by methods of that class.

To invoke a method, you provide an object reference to the target object and the method name, separated by a dot. Arguments are passed to the method as a comma-separated list of values enclosed in parentheses. Methods that take no arguments still require the parentheses, with nothing between them.

A method can return only a single value as a result. To return more than one value from a method, you must create an object whose purpose is to hold return values in a single unit and then return that object.

When a method is invoked, the flow of execution leaves the current method and starts executing the body of the invoked method. When the invoked method has completed, the current method continues execution with the code after the method invocation. When we start executing the body of the method, the object that was the target of the method invocation is now the current or receiver object, from the perspective of that method. The arguments passed to the method are accessed via the parameters the method declared.

Here is a method called distance that's part of the Point class shown in previous examples. The distance method accepts another Point object as a parameter, computes the Euclidean distance between itself and the other point, and returns a double-precision floating-point result:

public double distance(Point that)
{
double xdiff = x - that.x;
double ydiff = y - that.y;
return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
}

The return statement causes a method to stop executing its body and return execution to the invoking method. If an expression is part of the return statement then the value of that expression is returned as the value of the method invocation. The type of the expression must be compatible with the return type defined for the method. In the example we use the sqrt method of the Math library class to calculate the square root of the sum of the squares of the differences between the two x and y coordinates.

Based on the lowerLeft and upperRight objects created previously, you could invoke distance this way:

double d = lowerLeft.distance(upperRight);

Here upperRight is passed as an argument to distance, which sees it as the parameter that. After this statement executes, the variable d contains the Euclidean distance between lowerLeft and upperRight.

The this Reference
Occasionally, the receiving object needs to know its own reference. For example, the receiving object might want to add itself to a list of objects somewhere. An implicit reference named this is available to methods, and this is a reference to the current (receiving) object. The following definition of clear is equivalent to the one just presented:

public void clear()
{
this.x = 0.0;
this.y = 0.0;
}

You usually use this as an argument to other methods that need an object reference. The this reference can also be used to explicitly name the members of the current object. Here's another method of Point named move, which sets the x and y fields to specified values:

public void move(double x, double y)
{
this.x = x;
this.y = y;
}

The move method uses this to clarify which x and y are being referred to. Naming the parameters x and y is reasonable, because you pass x and y coordinates to the method. But then those parameters have the same names as the fields, and therefore the parameter names hide the field names. If we simply wrote x= x we would assign the value of the x parameter to itself, not to the x field as required. The expression this.x refers to the object's x field, not the x parameter of move.

Static or Class Methods
Just as you can have per-class static fields, you can also have per-class static methods, often known as class methods. Class methods are usually intended to do operations specific to the class itself, usually on static fields and not on specific instances of that class. Class methods are declared using the static keyword and are therefore also known as static methods.

As with the term "field", the word "method" generally means a per-object method, although the term non-static method is sometimes used for clarity.

Why would you need static methods? Consider the Sony Walkman factory again. The record of the next serial number to be assigned is held in the factory, not in every Walkman. A method that returned the factory's copy of the next available serial number would be a static method, not a method to operate on specific Walkman objects.

The implementation of distance in the previous example uses the static method Math.sqrt to calculate a square root. The Math class supports many methods that are useful for general mathematical manipulation. These methods are declared as static methods because they do not act on any particular instance of the Math class; instead, they group a related set of functionality in the class itself.

A static method cannot directly access non-static members. When a static method is invoked, there's no specific object for the method to operate on, and so no this reference. You could work around this by passing an explicit object reference as an argument to the static method. In general, however, static methods perform class-related tasks and non-static methods perform object-related tasks. Asking a static method to work on object fields is like asking the Walkman factory to change the serial number of a Walkman hanging on the belt of a jogger in Golden Gate Park.

We Are Founder..