Thursday, December 3, 2009

Java Exception

0comments

What Exceptions Are

Download Sample SouceCode :Exception.zip

Exceptions are objects that describe any error caused by an external resource not being available or an internal processing problem. They are passed to exception handlers written by the programmer to enable graceful recovery. If the handler has not been written, the program will terminate with a display of the Exception class. There are many exception classes such as IOException and NumberFormatException.

Exception Handling

Exception handling is a method of trapping or coping with anticipated errors (system, data entry or calculation) and handling or dealing with them in a graceful manner. The Exception class of objects offers a rich group of subclasses to trap specific errors and recover from them.
A thread is the flow of execution of a single set of program statements. Multithreading consists of multiple sets of statements which can be run in parallel. With a single processor only one thread can run at a time but strategies are used to make it appear as if the threads are running simultaneously. Depending on the operating system, either timeslicing or interrupt methods will move the processing from one thread to the next.


Checked and Unchecked Exceptions

  • Two kinds of exceptions, checked and unchecked.
  • Anything from a runtime exception is an unchecked exception. Meaning you don't have to provided a try/catch block. Subclasses of Error or RuntimeException.

try/catch block

The code that might throw an exception is enclosed in the try block. One or more catch clauses can be provided to handle different exception types:
 
  try 
  {
    // code that might throw exceptions
  }
  catch(Exception e)
  { 
    //code to handle the exception 
  }

finally block

The finally block can also be provided to perform any cleanup operation. If an exception is thrown, any matching catch clauses are executed, then control comes to the finally block, if one is provided. The syntax of the finally block is as follows:
 
  try 
  {
    // code that throws exceptions
  }
  catch(Exception e)
  {
    // handle exception
  }
  finally
  {
    // cleanup code
  }

The finally block is executed even if no exception is thrown. The only case in which this does not happen is when System.exit() is invoked by the try or catch blocks. A try block should have either a catch block or a finally block, but it's not required to have both.

Example
/**
*
* @author Arunkumar Subramaniam
*
*/
public class Test {
public static void main(String s[]){
try{ int i=0;
i=10/i;
}catch(Exception e){
System.out.println(e);
}
}
}

or

/**
*
* @author Arunkumar Subramaniam
*
*/
public class Test {
public static void main(String s[]){
try{
int i=0;
i=10/i;
}catch(ArithmeticException e){
System.out.println(e);
}catch(Exception e){
System.out.println(e);
}
}
}


Throws And Throw

throw is used to throw an exception manually, where as throws is used in the case of checked exceptions, to reintimate the compiler that we have handled the exception. so throws is to be used at the time of defining a method and also at the time of calling that function, which rises an checked exception.

/**
*
* @author Arunkumar Subramaniam
*
*/
public class Test {
void hello() throws ArithmeticException ,Exception {
try{
int i=0;
i=10/i;
}catch(ArithmeticException e){
throw new ArithmeticException();
}

}

void altHello() throws ArithmeticException ,Exception{
int i=0;
i=10/i;

}

public static void main(String s[]){
Test t=new Test();

try {
t.altHello();

} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

try {
t.hello();
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
}


User Defined Exception

Programmers could also create user-defined exceptions, specific to their business. Let's say you are in business selling bikes and need to validate a customers order. Create a new class TooManyBikesException that is derived from the class Exception or Throwable, and if someone tries to order more bikes than you can ship - just throw this exception:

/**
*
* @author Arunkumar Subramaniam
*
*/

public class ArunException extends Exception{

public ArunException(Exception e){
super(e);
}


}

/**
*
* @author Arunkumar Subramaniam
*
*/
public class TestException {

void hello()throws ArunException{
try{
int i=0;
i=10/i;
}catch(ArithmeticException e){
throw new ArunException(e);
}
}

void altHello()throws Exception{

int i=10;
i=10/i;
if(i==1){
throw new ArunException(new Exception("by mi2arun"));
}
}


public static void main(String str[]){
TestException t=new TestException();
try {
t.hello();
} catch (ArunException e) {
e.printStackTrace();
}
try {
t.altHello();
} catch (ArunException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

output :

ArunException: java.lang.ArithmeticException: / by zero
at TestException.hello(TestException.java:9)
at TestException.main(TestException.java:26)
Caused by: java.lang.ArithmeticException: / by zero
at TestException.hello(TestException.java:7)
... 1 more
ArunException: java.lang.Exception: by mi2arun
at TestException.altHello(TestException.java:18)
at TestException.main(TestException.java:31)
Caused by: java.lang.Exception: by mi2arun
... 2 more

Java Collections & Maps

0comments

Interfaces

>The symbols shown in the figure above define interfaces. They can only be used as attribute definition, not as instantiation class names:

Collection xx = null;
xx = new Collection ( ); // error !
Set yy = null;
SortedSet zz = null;

The figure also provides the directions of the dependencies.

xx = yy;
xx = zz;
yy = xx; // error !

Corresponding Implementations

Implementations
Hash Table
Resizable Array
Balanced Tree
Linked List
Interfaces
Collection
HashSet
ArrayList
TreeSet
LinkedList
Set
HashSet
TreeSet
SortedSet
TreeSet
List
ArrayList
LinkedList
Map
HashMap
TreeMap
SortedMap
TreeMap

The table above defines the implementations that correspond to the interfaces shown in the previous figure. An object defined by an interface must be instantiated by means of a class lying on the same line as the interface :

Collection xx1 = new HashSet ( ); // HashSet on the same line as Collection
Collection xx2 = new ArrayList ( );

SortedSet yy = new TreeSet ( );

Of course each collection can also be instantiated under its proper class:

ArrayList al = new ArrayList ( );

Main Characteristics of the Collections and Maps

All collections are used in a very similar way. What changes is the way in which the elements are stored in the collection:

ordered, with duplicates, with an access based on a key...

Moreover, some accesses may be more efficient in a collection or another one:

an ArrayList is created with an extra capacity, it must not be reallocated each time it grows
a LinkedList and an ArrayList can be used to create a fifo (list.add() / list.remove(0))
a TreeMap and a TreeSet are ordered (and thus need comparators)
a Set and a Map cannot contain duplicates
a Map contains pairs of (key;object). the elements are ordered and can be accessed by the key
the elements of some collections can be addressed by index
the collections can be walked through sequentially (iterator)
to walk through a Map, a collection must first be extracted

(see details below).

Storing Objects in a Collection or a Map

The basic methods to insert objects into a collection are given below:

HashSet, TreeSet

set.add(object);

add somewhere, in the order of the elements

LinkedList

list.add(object);
list.add(index, object);

adds at the end
adds at index and shifts the previous
elements from index towards the end

ArrayList

list.add(object)
list.add(index, object);
list.set(index,object);

adds at the end
adds at index and shifts the previous elements
overwrite the value at index

The basic methods to insert objects into a map are indicated below:

HashMap
TreeMap

map.put(key,value);

both key and value are Objects
in the tree maps, keys are put in order of the keys

Note: the aggregations that store the objects in an ordered manner (TreeSet and TreeMap) must know how to compare the inserted objects (respectively keys). There are two ways to do that:

  • have the objects (respectively keys) that are inserted in the tree aggregation implement Comparable

  • provide a Comparator in the parameters of the instantiation of the aggregation

  • Retrieving and Managing Objects in a Collection or a Map

    Some methods are known by all aggregations:

    clear( ); size( ); remove (object);

    Some of the methods defined in a collection are given below:

    LinkedList

    obj = c.get(index);

    obj = c.remove(index);

    bool = c.contains(obj);

    objArr = c.toArray( );

    ArrayList

    obj = c.get(index);

    obj = c.remove(index);

    bool = c.contains(obj);

    objArr = c.toArray( );

    HashSet

    -

    see 1 inch above

    bool = c.contains(obj);

    objArr = c.toArray( );

    TreeSet

    -

    see 1 inch above

    bool = c.contains(obj);

    objArr = c.toArray( );

    Some of the methods defined in a map are defined below (Object obj, key;) :

    HashMap
    TreeMap

    obj = m.get (key);

    obj = m.remove (key);

    bool = m.containsKey (key);
    bool = m.containsValue( key);

    collection = m.values( );
    set = m.keySet( );

    The operations of the last column return collections of elements. These collections can be used to walk through the trees.

    Transformations

    Passing from one aggregation type to another one can be used to sort the elements, eliminate the duplicates, create an array, and so on.

    A collection of any type can be transformed to another one:

    Set set = new HashSet ( );
    .... fill in the set ....
    SortedSet ss = new TreeSet ( set );

    Parameter available for the instantiation:

    LinkedList

    ( )

    (Collection)

    ArrayList

    ( )

    (Collection)

    (initialCapacity)

    HashSet

    ( )

    (Collection)

    (initialCapacity)

    (initialCapacity, loadFactor)

    HashMap

    ( )

    (Map)

    (initialCapacity)

    (initialCapacity, loadFactor)

    TreeSet

    ( )

    (Collection)

    (Comparator)

    (SortedSet)

    TreeMap

    ( )

    (Map)

    (Comparator)

    (SortedMap)

    The maps return collections containing only the objects (keys are dropped)

    Collection col = tm.values();

    which can used as parameter in the instantiation of a collection.

    A collection can be transformed into an array with:

    Object [] obj = collection.toArray();

    Java Inner Class

    0comments

    What are Nested/Inner classes.

    Download SampleCode:Outter.java

    Up until the introduction of Jdk 1.1, the java language only supported top-level classes. Top level classes are classes that are defined as members of a package. But with Jdk 1.1, sun introduced the concept of nested/inner classes in java. Nested/inner classes are classes within classes. Inner/Nested classes makes it much easier for developer to connect object together, since classes can be defined closer to the objects. First of all before you go any further, you must know that this feature of java is only limited to the compiler. In other words to compile java code that contains nested/inner classes, you will need Jdk 1.1 or later but the compiled code can be executed on any jvm. You've probably used inner classes already in java without noticing it. A typical example of the usage of an inner class is when creating an adapter class to listen to events in a GUI. Nested/inner classes gives a developer lots of power, but when they are not properly use or understood, they can be very confusing. Here is the main difference between Nested and Inner classes

    Nested class

    A nested class has the same behavior as any static member of a class. You can have access to it without initializing the parent class, and they can access the parent class static methods and variables also. Nested classes are always define with the keyword static (and we will see later that this is what differentiate them from the inner classes). An access tag (i.e. : public, protected or private) can be defined, but by default a nested class takes the default package access. Sun considers nested classes to be top-level classes (I find this at times to be confusing). Here is an example of how to define a nested class MyInner in the class enclosing class MyOuter.

    class MyOuter {

    public static class MyInner {
    //...
    public void function1() {}
    //more function (static and more)
    }
    }

    Notice that when you compile this code, you will have two .class file as the output :

    MyOuter.class : being the enclosing class.

    MyOuter$MyInner.class : being the inner class. Since class MyInner is a static member of MyOuter, it can be access from anywhere in your code using MyOuter.MyInner (The same way that you access classes in packages, you can even use the import statement with nested classes : import MyOuter.MyInner).

    Example :

    Here is the code to call the constructor of class MyInner anywhere in your code :

     public MyInner myclass = MyOuter.MyInner();

    However, if the class MyOuter was define in the package my.package you will write :


    MyInner myclass = my.package.MyOuter.MyInner();

    As you can see you do not have to create an instance of class MyOuter to use class MyInner. Class MyOuter serves a package for class MyInner. Personally I would recommend not using Nested classes (unless you really think that no classes outside the scope your object would ever want to use the nested classes), most of the time, it is much easier and cleaner to define the class in a separate .java file instead.

    Inner Class

    Inner class differ very much from nested class because it does not have a static tag, as a matter of fact you can never write an inner class with the static tag (when you add the static tag it automatically becomes a nested class). Unlike a nested class, every instance of an inner class requires an instance of the enclosing class, and an enclosing class can have multiple instance of the inner class. Without going into too much details, here are the three types of inner class:

    Member inner classes

    This type of inner class is defined as members of the enclosing class, they are defined on the same level as function and variables of a class, and have the same behavior and properties.

    Example :
    class MyOuter
    {
    private float variable = 0;
    public void donothing() { //do your stuff }
    private class MyInner
    {
    public void innerfunction() {//do your stuff }
    public void function()
    {
    //Do your stuff
    //Here is how you call a function with the
    same name
    //from the enclosing class
    MyOutter.this.donothing();
    }
    }
    }

    The inner class MyInner class is a Member inner class. Notice in the example above, I had a name conflict with the enclosing class MyOuter when trying to call the function donothing(), that is why I added the line MyOuter.this.donothing(). This forces the compiler to get take the current instance of the enclosing class function instead.

    Local inner classes

    This type of inner class is defined inside a bloc of code. However, like any object they can live beyond the scope of the bloc of code inside witch they are defined, this depends on what you do with them.

    Example :
    Interface MyInterface
    {
    public String getInfo();
    }
    class MyOuter
    {
    MyInterface current_object;
    public void setInterface(String info)
    {
    class MyInner implement MyInterface
    {
    private String info;
    public MyInner(String inf) {info=inf;}
    public string getInfo() {return info;}
    }
    current_object = new MyInner(info);
    }
    }
    In the example above, the class MyInner is a local inner class.

    Anonymous inner classes

    This is a very special type of inner class. An anonymous inner class usually does not have a name. You probably used anonymous inner classes before. They are often used in GUI development to implement listeners. Here is an example of the most frequent use of anonymous inner class in java.

    Example :

    class Outer extends java.awt.Frame
    {
    public Outer()
    {
    java.awt.Button button = new java.awt.Button
    ("Click on me");
    button.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    System.out.println("You clicked");
    }
    });
    }
    }
    In the code above the class ActionListener is an anonymous class.

    Advantages of using Nested/Inner class

    Inner class be very powerful;l development tools when you know how to use them. Here are a just a few advantages that nested/inner classes can give you.

    Blocs of codes.

    One of the main reasons sun introduced Nested/Inner classes in java is to give developers the ability to implement blocs of codes, that can be used to realize special functions inside a given object (pointers to methods). Using inner classes you can integrate blocs of code inside your object to perform special task pretty much like you have method pointers in C.

    Integrate object in objects

    By giving the developers the ability to integrate blocs of code in objects via inner class, developer now have the ability to integrate objects in objects, this is a very big advantage since your code can now have a more object oriented design. You can create special objects as part of another object. In a way your code can become much easier to read, and also your code is more object oriented. Now it is possible to separate the logic in your objects in inner objects. Example if you have a class Engine, and you define an interface EnginePower in the same package. You can create a inner object that implement the interface EnginePower inside the class Engine for a specific type of engine (i.e. JetEngine). This is a pretty efficient method of coding since you know that the inner class EnginePower is tightly linked to the enclosing class Engine and the user would only want to access the EnginePower interface

    Callbacks.

    Inner class are also very useful when you want to implement callbacks. A very good example of the advantage of using an inner class for callbacks is when implementing GUI event listeners (see example above). If you try to implement the callback procedure mention in the example for anonymous inner class without inner class, then you will have to implement the ActionLlistener interface in a class and this would force you to use a bunch of if and else if to figure out on which object the event occurred. Using inner classes allows you to efficiently have a separate bloc of code to do handle the actionPerformed function for every graphic component object.

    Java Reference Type Casting

    0comments
    In java one object reference can be cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java. The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.

    There can be 2 types of casting

    · Upcasting
    · Downcasting

    When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast.
    When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.


    The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship)
    At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.

    Below is an example showing when a ClassCastException can occur during object casting

        

    //X is a supper class of Y and Z which are sibblings.

    public class RunTimeCastDemo{
    public static void main(String args[]){
    X x = new X();
    Y y = new Y();
    Z z = new Z();

    X xy = new Y(); // compiles ok (up the hierarchy)
    X xz = new Z(); // compiles ok (up the hierarchy)
    // Y yz = new Z(); incompatible type (siblings)

    // Y y1 = new X(); X is not a Y
    // Z z1 = new X(); X is not a Z

    X x1 = y; // compiles ok (y is subclass of X)
    X x2 = z; // compiles ok (z is subclass of X)

    Y y1 = (Y) x; // compiles ok but produces runtime error
    Z z1 = (Z) x; // compiles ok but produces runtime error
    Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
    Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
    // Y y3 = (Y) z; inconvertible types (siblings)
    // Z z3 = (Z) y; inconvertible types (siblings)

    Object o = z;
    Object o1 = (Y)o; // compiles ok but produces runtime error

    }
    }


    Casting Object References: Implicit Casting using a Java Compiler


    In general an implicit cast is done when an Object reference is assigned (cast) to:

    • A reference variable whose type is the same as the class from which the object was instantiated.
      An Object as Object is a super class of every Java Class.
    • A reference variable whose type is a super class of the class from which the object was instantiated.
    • A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
    • A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.


    Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the automatic conversion of object references handled by the java compiler


       interface Vehicle {
    }
    class Car implements Vehicle {
    }

    class Ford extends Car {
    }



    Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign the Ford reference to the Car variable:
    I.e. we can do the following

    Example 1
    c = f; //Ok Compiles fine

    Where c = new Car();
    And, f = new Ford();
    The compiler automatically handles the conversion (assignment) since the types are compatible (sub class - super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.


    Example 2
    v = c; //Ok Compiles fine
    c = v; // illegal conversion from interface type to class type results in compilation error

    Where c = new Car();
    And v is a Vehicle interface reference (Vehicle v)

    The compiler automatically handles the conversion (assignment) since the types are compatible (class – interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is a Vehicle).

    Casting Object References: Explicit Casting

    Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario. The explicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. As before, we consider the same Car and Ford Class


    class Car {
    void carMethod(){
    }
    }

    class Ford extends Car {
    void fordMethod () {
    }
    }

    We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter.
    The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.

    public void breakingSystem (Car obj) {
    obj.carMethod();
    if (obj instanceof Ford)

    ((Ford)obj).fordMethod ();
    }

    To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition.

    The following java shown illustrates the use of the cast operator with references.

    Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the object's reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford.
    In order to use a reference of a class type to invoke a method, the method must be defined at or above that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object reference as done in the program.
    Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happens without any error.

     class Car extends Object{
    void carMethod() {
    }
    }

    class HeavyVehicle extends Object{

    }

    class Ford extends Car {
    void fordMethod () {
    System.out.println("I am fordMethod defined in Class Ford");
    }
    }

    class Honda extends Car {
    void fordMethod () {
    System.out.println("I am fordMethod defined in Class Ford");
    }
    }




    public class ObjectCastingEx{
    public static void main(
    String[] args){
    Car obj = new Ford();
    // Following will result in compilation error
    // obj.fordMethod(); //As the method fordMethod is undefined
    for the Car Type
    // Following will result in compilation error
    // ((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in
    the HeavyVehicle Type
    // Following will result in compilation error

    ((Ford)obj).fordMethod();

    //Following will compile and run
    // Honda hondaObj = (Ford)obj; Cannot convert as they are sibblings

    }
    }

    One common casting that is performed when dealing with collections is, you can cast an object reference into a String.

      import java.util.Vector;

    public class StringCastDemo{
    public static void main(String args[]){
    String username = "asdf";
    String password = "qwer";
    Vector v = new Vector();
    v.add(username);
    v.add(password);


    // String u = v.elementAt(0); Cannot convert from object to String
    Object u = v.elementAt(0); //Cast not done
    System.out.println("Username : " +u);


    String uname = (String) v.elementAt(0); // cast allowed
    String pass = (String) v.elementAt(1); // cast allowed

    System.out.println();
    System.out.println("Username : " +uname);
    System.out.println("Password : " +pass);
    }
    }

    Output

    Username : asdf

    Username : asdf
    Password : qwer

    Java Abstract Class

    0comments

    Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

    Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

    Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.

    A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

        abstract class Vehicle {
    int numofGears;
    String color;
    abstract boolean hasDiskBrake( );
    abstract int getNoofGears( );
    }

      abstract class Vehicle {
    int numofGears;
    String color;
    abstract boolean hasDiskBrake( );
    abstract int getNoofGears( );
    }

    We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

     public class Point extends Shape {
    static int x, y;
    public Point( ) {
    x = 0;
    y = 0;
    }

    public double area( ) {
    return 0;
    }

    public double perimeter( ) {
    return 0;
    }

    public static void print( ){
    System.out.println ( "point: " + x + "," + y );
    }

    public static void main(String args[]){
    Point p = new Point();
    p.print();
    }

    }

    Output

    point: 0, 0

    Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class.

    The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.

    A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

    Java Interface

    0comments

    In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.

    Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.

    If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.

    Below is an example of a Shape interface

       interface Shape {
    public double area( );
    public double volume( );
    }

    Below is a Point class that implements the Shape interface.

      public class Point implements Shape {
    static int x, y;
    public Point( ) {
    x = 0;
    y = 0;
    }

    public double area( ) {
    return 0;
    }

    public double volume( ) {
    return 0;
    }

    public static void print( ){
    System.out.println ( "point: " + x + "," + y );
    }

    public static void main(String args[]){
    Point p = new Point();
    p.print();
    }

    }

    Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface.

    Below is a java interfaces program showing the power of interface programming in java

    Listing below shows 2 interfaces and 4 classes one being an abstract class.
    Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract.
    Also,
    i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.

    When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are "siblings". You can't cast siblings into one another.

    When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.

    interface I1{
    void methodI1(); //public static by default
    }

    interface I2 extends I1{
    void methodI2(); //public static by default
    }

    class A1{
    public String methodA1(){
    String strA1 = "I am in methodC1 of class A1";
    return strA1;
    }

    public String toString(){
    return "toString() method of class A1";
    }
    }
    class B1 extends A1 implements I2{
    public void methodI1(){
    System.out.println("I am in methodI1 of class B1");
    }

    public void methodI2(){
    System.out.println("I am in methodI2 of class B1");
    }
    }

    class C1 implements I2{
    public void methodI1(){
    System.out.println("I am in methodI1 of class C1");
    }

    public void methodI2(){
    System.out.println("I am in methodI2 of class C1");
    }
    }

    // Note that the class is declared as abstract as it does not
    //satisfy the interface contract
    abstract class D1 implements I2{
    public void methodI1() {
    }

    //This class does not implement methodI2() hence declared abstract.

    }
    public class InterFaceEx{
    public static void main(String[] args){
    I1 i1 = new B1();
    i1.methodI1(); //OK as methodI1 is present in B1
    // i1.methodI2(); Compilation error as methodI2 not present in I1

    // Casting to convert the type of the reference from type I1 to type I2
    ((I2)i1).methodI2();

    I2 i2 = new B1();
    i2.methodI1(); //OK
    i2.methodI2(); //OK

    // Does not Compile as methodA1() not present in interface reference I1
    // String var = i1.methodA1();

    //Hence I1 requires a cast to invoke methodA1

    String var2 = ((A1)i1).methodA1();
    System.out.println("var2 : "+var2);
    String var3 = ((B1)i1).methodA1();
    System.out.println("var3 : "+var3);
    String var4 = i1.toString();
    System.out.println("var4 : "+var4);
    String var5 = i2.toString();
    System.out.println("var5 : "+var5);

    I1 i3 = new C1();
    String var6 = i3.toString();
    System.out.println("var6 : "+var6);
    //It prints the Object toString() method

    Object o1 = new B1();
    // o1.methodI1(); does not compile as Object class
    does not define methodI1()
    //To solve the probelm we need to downcast o1 reference.
    We can do it in the following 4 ways
    ((I1)o1).methodI1(); //1
    ((I2)o1).methodI1(); //2
    ((B1)o1).methodI1(); //3

    /*
    * B1 does not have any relationship with C1 except they are "siblings".
    * Well, you can't cast siblings into one another.
    */
    // ((C1)o1).methodI1(); Produces a ClassCastException



    }
    }


    Output

    I am in methodI1 of class B1
    I am in methodI2 of class B1
    I am in methodI1 of class B1
    I am in methodI2 of class B1
    var2 : I am in methodC1 of class A1
    var3 : I am in methodC1 of class A1
    var4 : toString() method of class A1
    var5 : toString() method of class A1
    var6 : C1@190d11
    I am in methodI1 of class B1
    I am in methodI1 of class B1
    I am in methodI1 of class B1

    Polymorphism

    Polymorphism means one name, many forms. There are 3 distinct forms of Java Polymorphism; Method overloading (Compile time polymorphism) Method overriding through inheritance (Run time polymorphism) Method overriding through the Java interface (Run time polymorphism) Polymorphism allows a reference to denote objects of different types at different times during execution. A super type reference exhibits polymorphic behavior, since it can denote objects of its subtypes.
        interface Shape {
    public double area( );
    public double volume( );
    }

    class Cube implements Shape {
    int x= 10;

    public double area( ) {
    return (6 * x * x);
    }

    public double volume( ) {
    return (x * x * x);
    }
    }

    class Circle implements Shape {
    int radius = 10;

    public double area( ) {
    return (Math.PI * radius * radius);
    }

    public double volume( ) {
    return 0;
    }

    }

    public class PolymorphismTest{
    public static void main(String args[]){
    Shape[] s = {new Cube(), new Circle()};

    for( int i = 0; i< s.length; i++){
    System.out.println("The area and volume of "+s[i].getClass()
    + " is "+s[i].area()+" , "+s[i].volume());
    }
    }
    }

    Output

    The area and volume of class Cube is 600.0 , 1000.0
    The area and volume of class Circle is 314.1592653589793 , 0.0

    Java Wrapper Class

    0comments

    Wrapper classes correspond to the primitive data types in the Java language. These classes represent the primitive values as objects. All the wrapper classes except Character have two constructors -- one that takes the primitive value and another that takes the String representation of the value. For instance:

        Integer i1 = new Integer(50);    Integer i2 = new Integer("50");  

    The Character class constructor takes a char type element as an argument:

        Character c = new Character('A');  

    Wrapper objects are immutable. This means that once a wrapper object has a value assigned to it, that value cannot be changed.

    The valueOf() method

    All wrapper classes (except Character) define a static method called valueOf(), which returns the wrapper object corresponding to the primitive value represented by the String argument. For instance:
        Float f1 = Float.valueOf("1.5f");  

    The overloaded form of this method takes the representation base (binary, octal, or hexadecimal) of the first argument as the second argument. For instance:

        Integer I = Integer.valueOf("10011110",2);  

    Converting wrapper objects to primitives

    All the numeric wrapper classes have six methods, which can be used to convert a numeric wrapper to any primitive numeric type. These methods are byteValue, doubleValue, floatValue, intValue, longValue, and shortValue. An example is shown below:
        Integer i = new Integer(20);    byte b = i.byteValue();  

    Parser methods

    The six parser methods are parseInt, parseDouble, parseFloat, parseLong, parseByte, and parseShort. They take a String as the argument and convert it to the corresponding primitive. They throw a NumberFormatException if the String is not properly formed. For instance:
        double d = Double.parseDouble("4.23");  

    It can also take a radix(base) as the second argument:

        int i = Integer.parseInt("10011110",2);  

    Base conversion

    The Integer and Long wrapper classes have methods like toBinaryString() and toOctalString(), which convert numbers in base 10 to other bases. For instance:
        String s = Integer.toHexString(25);  
     

    JAVA INTRODUCTION Blak Magik is Designed by productive dreams for smashing magazine Bloggerized by Ipiet © 2008