Friday, January 30, 2009

Abstract Methods and Classes  

0 comments

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. 

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: 
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in: 
public abstract class GraphicObject {
  // declare fields
  // declare non-abstract methods
  abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.


Abstract Classes versus Interfaces:


Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead. 


Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example. 

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

When an Abstract Class Implements an Interface:


In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example, 
abstract class X implements Y {
  // implements all but one method of Y
}

class XX extends X {
  // implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y. 

Class Members:


An abstract class may have static fields and static methods. You can use these static members with a class reference—for example, AbstractClass.staticMethod()—as you would with any other class.


Writing Final Classes and Methods  

0 comments

You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final. 

You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final: 
class ChessAlgorithm {
  enum ChessPlayer { WHITE, BLACK }
  ...
  final ChessPlayer getFirstPlayer() {
  return ChessPlayer.WHITE;
  }
  ...
}
Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. 

Note that you can also declare an entire class final — this prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class.

Object as a Superclass  

0 comments

The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. The methods inherited from Object that are discussed in this section are: 
protected Object clone() throws CloneNotSupportedException
  Creates and returns a copy of this object. 
public boolean equals(Object obj)
  Indicates whether some other object is "equal to" this one. 
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 
public final Class getClass()
  Returns the runtime class of an object. 
public int hashCode()
  Returns a hash code value for the object. 
public String toString()
  Returns a string representation of the object. 


The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program, which is discussed in a later lesson and won't be covered here. There are five of these methods: 
public final void notify() 
public final void notifyAll() 
public final void wait() 
public final void wait(long timeout) 

public final void wait(long timeout, int nanos)

Note: There are some subtle aspects to a number of these methods, especially the clone method. You can get information on the correct usage of these methods in the book Effective Java by Josh Bloch.

Keyword super  

0 comments

Accessing Superclass Members
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass: 
public class Superclass {

  public void printMethod() {
  System.out.println("Printed in Superclass.");
  }
}
Here is a subclass, called Subclass, that overrides printMethod(): 
public class Subclass extends Superclass {

  public void printMethod() { //overrides printMethod in Superclass
  super.printMethod();
  System.out.println("Printed in Subclass");
  }
  public static void main(String[] args) {
   
  Subclass s = new Subclass();
  s.printMethod(); 
  }

}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following: 
Printed in Superclass.
Printed in Subclass
Subclass Constructors
The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own: 
  public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
  super(startCadence, startSpeed, startGear);
  seatHeight = startHeight;
  } 
Invocation of a superclass constructor must be the first line in the subclass constructor. 

The syntax for calling a superclass constructor is 
super();  
--or--
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.


Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

c and Hiding Methods  

0 comments

Instance Methods


An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. 

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. 

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations. 

Class Methods


If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. 

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method: 
public class Animal {
  public static void testClassMethod() {
  System.out.println("The class method in Animal.");
  }
  public void testInstanceMethod() {
  System.out.println("The instance method in Animal.");
  }
}
The second class, a subclass of Animal, is called Cat: 
public class Cat extends Animal {
  public static void testClassMethod() {
  System.out.println("The class method in Cat.");
  }
  public void testInstanceMethod() {
  System.out.println("The instance method in Cat.");
  }

  public static void main(String[] args) {
  Cat myCat = new Cat();
  Animal myAnimal = myCat;
  Animal.testClassMethod();
  myAnimal.testInstanceMethod();
  }
}
The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance. 

The output from this program is as follows: 
The class method in Animal.
The instance method in Cat.
As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

Inheritance  

0 comments

Definitions: 


 

A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). 

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object. 

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

Summary of Interfaces  

0 comments

An interface defines a protocol of communication between two objects. 

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions. 

A class that implements an interface must implement all the methods declared in the interface. 

An interface name can be used anywhere a type can be used.

Rewriting Interfaces  

0 comments

Consider an interface that you have developed called DoIt: 
public interface DoIt {
  void doSomething(int i, double x);
  int doSomethingElse(String s);
}
Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: 
public interface DoIt {

  void doSomething(int i, double x);
  int doSomethingElse(String s);
  boolean didItWork(int i, double x, String s);
   
}
If you make this change, all classes that implement the old DoIt interface will break because they don't implement the interface anymore. Programmers relying on this interface will protest loudly. 

Try to anticipate all uses for your interface and to specify it completely from the beginning. Given that this is often impossible, you may need to create more interfaces later. For example, you could create a DoItPlus interface that extends DoIt: 
public interface DoItPlus extends DoIt {

  boolean didItWork(int i, double x, String s);
   
}
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface

Implementing an Interface  

0 comments

A Sample Interface, Relatable


Consider an interface that defines how to compare the size of objects. 

public interface Relatable {
 
  // this (object calling isLargerThan) and
  // other must be instances of the same class
  // returns 1, 0, -1 if this is greater

  // than, equal to, or less than other

  public int isLargerThan(Relatable other);

   

Implementing the Relatable Interface
Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable. 
public class RectanglePlus implements Relatable {
  public int width = 0;
  public int height = 0;
  public Point origin;

  // four constructors
  public RectanglePlus() {
 origin = new Point(0, 0);
  }
  public RectanglePlus(Point p) {
 origin = p;
  }
  public RectanglePlus(int w, int h) {
 origin = new Point(0, 0);
 width = w;
 height = h;
  }
  public RectanglePlus(Point p, int w, int h) {
 origin = p;
 width = w;
 height = h;
  }

  // a method for moving the rectangle
  public void move(int x, int y) {
 origin.x = x;
 origin.y = y;
  }

  // a method for computing the area of the rectangle
  public int getArea() {
 return width * height;
  }
   
  // a method to implement Relatable
  public int isLargerThan(Relatable other) {
  RectanglePlus otherRect = (RectanglePlus)other;
  if (this.getArea() < otherRect.getArea())
  return -1;
  else if (this.getArea() > otherRect.getArea())
  return 1;
  else
  return 0;  
  }
}
Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared.

defining an interface  

0 comments

An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example: 
public interface GroupedInterface extends Interface1,
  Interface2, Interface3 {

  // constant declarations
  double E = 2.718282; // base of natural logarithms

  // method signatures
  void doSomething (int i, double x);
  int doSomethingElse(String s);

}
The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface. 

An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

what is interface?  

0 comments

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts. 

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning Satellite) position data and wireless transmission of traffic conditions and use that information to drive the car. 

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces

0 comments

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false:
If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

The following is one example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}


prints the following output:
this
is
a
test


StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to break up a string into its basic tokens:
String[] result = "this is a test".split("\\s");
for (int x=0; x System.out.println(result[x]);


prints the following output:
this
is
a
test

this is available Since: JDK1.0

Wednesday, January 28, 2009

IO system writer class  

0 comments

IO system reader class  

0 comments

IO system output class  

0 comments

IO system input class  

0 comments


Wrapper Classes -- methods with examples  

0 comments

There are some of the methods of the Wrapper class which are used to manipulate the data. Few of them are given below:

1. add(int, Object): Learn to insert an element at the specified position.

2. add(Object): Learn to insert an object at the end of a list.

3. addAll(ArrayList): Learn to insert an array list of objects to another list.

4. get(): Learn to retrieve the elements contained with in an ArrayList object.

5. Integer.toBinaryString(): Learn to convert the Integer type object to a String object.

6. size(): Learn to get the dynamic capacity of a list.

7. remove(): Learn to remove an element from a particular position specified by a index value. 

8. set(int, Object): Learn to replace an element at the position specified by a index value.

Wrapper Classes  

0 comments

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper 
classes, because they "wrap" the primitive data type into an object of that class. So, there is an 
Integer class that holds an int variable, there is a Double class that holds a double 
variable, and so on. The wrapper classes are part of the java.lang package, which is imported 
by default into all Java programs. The following discussion focuses on the Integer wrapper 
class, but applies in a general sense to all eight wrapper classes. Consult the Java API 
documentation for more details. 
The following two statements illustrate the difference between a primitive data type and an object 
of a wrapper class: 
int x = 25; 
Integer y = new Integer(33); 
The first statement declares an int variable named x and initializes it with the value 25. The 
second statement instantiates an Integer object. The object is initialized with the value 33 and 
a reference to the object is assigned to the object variable y. The memory assignments from 
these two statements are visualized in Figure 1. 


Clearly x and y differ by more than their values: x is a variable that holds a value; y is an object 
variable that holds a reference to an object. As noted earlier, data fields in objects are not, in 
general, directly accessible. So, the following statement using x and y as declared above is not 
allowed: 
int z = x + y; // wrong! 
The data field in an Integer object is only accessible using the methods of the Integer class.  
One such method — the intValue() method — returns an int equal to the value of the 
object, effectively "unwrapping" the Integer object: 
int z = x + y.intValue(); // OK! 
Note the format of the method call. The intValue() method is an instance method, because it 
is called through an instance of the class — an Integer object. The syntax uses dot notation, 
where the name of the object variable precedes the dot. 
Some of Java's classes include only instance methods, some include only class methods, some 
include both. The Integer class includes both instance methods and class methods. The class 
methods provide useful services; however, they are not called through instances of the class.  
But, this is not new. We met a class method of the Integer class earlier. The statement  
int x = Integer.parseInt("1234"); 
converts the string "1234" into the integer 1,234 and assigns the result to the int variable x.  
The method parseInt() is a class method. It is not called through an instance of the class.  

Although dot notation is used above, the term "Integer." identifies the class where the method 
is defined, rather than name of an Integer object. This is one of the trickier aspects of 
distinguishing instance methods from class methods. For an instance method, the dot is preceded 
by the name of an object variable. For a class method, the dot is preceded by the name of a class.  
It is interesting that the parseInt() method accepts a String argument and returns an int.  
Neither the argument nor the returned value is an Integer object. So, the earlier comment that 
class methods "provide useful services" is quite true. They do not operate on instance variables; 
they provide services that are of general use. The parseInt() method converts a String to 
an int, and this is a useful service — one we have called upon in previous programs. 
Another useful Integer class method is the toString() method. The following statement 
String s = Integer.toString(1234); 
converts the int constant 1,234 to a String object and returns a reference to the object. We 
have already met this method through the following shorthand notation: 
String s = "" + 1234; 

The most common methods of the Integer wrapper class are summarized in Table 1. Similar 
methods for the other wrapper classes are found in the Java API documentation. 
Table 1. Methods of the Integer Wrapper Class 
Method Purpose 
Constructors 
Integer(i)  constructs an Integer object equivalent to the integer i 
Integer(s)  constructs an Integer object equivalent to the string s 
Class Methods 
parseInt(s)  returns a signed decimal integer value equivalent to string s 
toString(i)   returns a new String object representing the integer i 
Instance Methods 
byteValue()   returns the value of this Integer as a byte 
doubleValue()   returns the value of this Integer as an double 
floatValue()   returns the value of this Integer as a float 
intValue()   returns the value of this Integer as an int 
longValue()   returns the value of this Integer as a long 
shortValue()   returns the value of this Integer as a short 

In the descriptions of the instance methods, the phrase "this Integer" refers to the instance 
variable on which the method is acting. For example, if y is an Integer object variable, the 
expression y.doubleValue() returns the value of "this Integer", or y, as a double.

Monday, January 19, 2009

past 13 years, Java has changed our world  

0 comments

For the past 13 years, Java has changed our world . . . and our expectations..

Today, with technology such a part of our daily lives, we take it for granted that we can be connected and access applications and content anywhere, anytime. Because of Java, we expect digital devices to be smarter, more functional, and way more entertaining.

In the early 90s, extending the power of network computing to the activities of everyday life was a radical vision. In 1991, a small group of Sun engineers called the "Green Team" believed that the next wave in computing was the union of digital consumer devices and computers. Led by James Gosling, the team worked around the clock and created the programming language that would revolutionize our world – Java.

The Green Team demonstrated their new language with an interactive, handheld home-entertainment controller that was originally targeted at the digital cable television industry. Unfortunately, the concept was much too advanced for the them at the time. But it was just right for the Internet, which was just starting to take off. In 1995, the team announced that the Netscape Navigator Internet browser would incorporate Java technology.

Today, Java not only permeates the Internet, but also is the invisible force behind many of the applications and devises that power our day-to-day lives. From mobile phones to handheld devises, games and navigation systems to e-business solutions, Java is everywhere!

History by years  

0 comments

The Java History Timeline

1991 

The Green Project Begins
MS DOS is the dominant operating system
Cell phones weigh half a pound
"Biosphere 2" project begins

1992

"Oak" is the language 
*7 Debuts
"Duke" is featured in the Interface
Johnny Carson signs off "The Tonight Show" on NBC

1993 

The Green Project becomes FirstPerson
Mosaic v1.0 is released
"Cheers" ends an 11-year run

1994 

WebRunner released — the first browser that supports moving objects and dynamic executable content
The Apple QuickTake 100, the first consumer digital camera, goes on sale for less than $1,000 
"Friends" debuts on NBC

1995 

Java technology released to a select group on the Web site wicked.neato.org
The San Jose Mercury News runs a front-page article about Java technology
Name changed from "Oak" to "Java"
Announced at Sun World -- Java technology is officially born

1996 

The first JavaOne Developer Conference
JDKtm 1.0 software is released
Chess computer Deep Blue defeats Garry Kasparov for the first time
"Dolly" the first cloned sheep is born

1997 

Over 220,000 downloads of JDK 1.1 software occur in just three weeks
JavaOne draws 8,000 attendees, becoming the world's largest developer conference
Java Card 2.0 platform is unveiled
43% of U.S. families own a computer

1998 

JDK 1.1 release downloads top 2 million
Visa launches world's first smart card based on Java Card technology
The Java Community Process (JCP) program formalized
"Who Wants to Be a Millionaire?" premieres in the U.K

1999 

Java 2 platform source code is released
JavaOne draws 20,000
J2EE beta software is released
"Star Wars Episode I: The Phantom Menace" released

2000 

Over 400 Java User Groups are established worldwide
Java Developer Connection program tops 1.5 million members
Steve Jobs joins Scott McNealy on stage at JavaOne to announce a major commitment by Apple in support of Java technology
Heavy Metal band Metallica sues Napster for copyright violations

2001 

First international JavaOne conference in Yokohama Japan
Over 1 million downloads of the Java Platform, Enterprise Edition (Java EE) SDK
Google Inc. PageRank search algorithm patent awarded
"The Lord of the Rings: The Fellowship of the Ring" is released

2002 

J2EE SDK downloads reach 2 million
78% of executives view J2EE technology as the most effective platform for building and deploying Web services
The Euro is introduced
"The Osbournes" becomes a surprise hit on MTV

2003 

Java technology runs in almost 550 million desktops
Almost 75% of professional developers use Java programming language as their primary development language
Commercial Voice-Over-Internet (VoiP) phone service begins
"The Da Vinci Code" is published

2004 

Java 2 Platform, Standard Edition 5 (Project Tiger) is released
The Java technology-powered Mars Rover (Spirit) touches down on Mars
Sun Java Studio Creator is launched

2005 

Java technology celebrates its 10th birthday
Approximately 4.5 million developers use Java technology
Over 2.5 billion Java technology-enabled devices are available
java.com bundles the Google Toolbar with the JRE download

2006 

Rich Green announces at the JavaOne 2006 Conference that it's not a matter of when Sun will open source Java technology, but how. The NetBeans IDE 5.0 is released. Sun open-sourced Java EE components as the Glassfish Project to java.net. Java SE and ME initial components are released as open source. Pirates of the Caribbean: Dead Man's Chest is released.

Extension Factory Builder