Blogger templates

Your Ad Here

Video

Blogroll

Blogger news

OpenLaszlo


Its a free open-source programming language alternative to FLEX


Its a new uprising technology to create so called Rich Internet Applications (RIA's), where the weapon of choice is Flash.
Quick facts about OpenLaszlo
  • OpenLaszlo is a similar to FLEX using XML and JavaScript, but the only difference is, its based on the idea of open source 
  • It can create both, Flash and DHTML/AJAX
  • OpenLaszlo goes down to Flash5, FLEX supports only version 7 and higher
  • It is coming for mobile applications using Sun's JavaME technology


Costs
Unlike FLEX, the user won't have to pay any money for neither the development server nor any IDE, which makes OpenLaszlo a quite nice alternative. All you need to develop Laszlo applications is the application server and an editor like notepad.


Flash or DHTML/AJAX output
OL can compile your code into either swf or transform the xml into clean DHTML/AJAX (html+javascript). This is probably the most astonishing feature in OpenLaszlo since both, the flash and the DHTML/AJAX version, have exactly the same look and feel.



FLEX vs OpenLaszlo
Which is better. FLEX or Laszlo? Where are the differences? What do they have in common ? Which is the right one for users?
First of all, both have a lot in common like the xml based syntax, the component model, javascript/actionscript and the modularity for additional third party code.
  • License policy
Its open source ie. Laszlo is completely free of charge. You won't have to pay for anything while Adobe charges at least for the FLEX IDE which is a quite nice tool for developers.

  • Popularity
After the assimilation of Macromedia by Adobe many common and well known web development applications like Dreamweaver or Flash belong to the creator of Photoshop, which makes it very easy to reach a wide popularity for their new products FLEX and AIR. Laszlo on the other side is only well known by insiders of the scene who seek for alternatives. Laszlo Systems, the creators of OpenLaszlo don't have the financial power like Adobe to run big advertisement campaigns. This leads to a big problem: The less a development platform is known, the fewer developers will produce code for third party plugins and modules. While there are quite a lot of pre-made scripts and modules out there for FLEX, the laszlo developer will have to build a lot by own hand.

  • Compatibility
An  advantage of openlaszlo is the ability to let the developer and the user choose whether to use a Flash version or the DHTML or AJAX. This helps to the compatibility problems with users, who don't have an updated version of their flash plugin installed or maybe no plugin at all. Laszlo developers have the big advantage at this point to simply transform their code into DHTML/AJAX code, which should work in every more or less modern browser.






Next : Setting up Openlaszlo development environment

Object Oriented Programming - Introduction

This tutorial can be used by a beginner irrespective of the knowledge in any programming language. Here I present only the basic idea about OOPS concept.
Classes, Objects, and Methods are the most basic concepts for object oriented programming. Besides, Inheritance, Abstraction, Polymorphism, Event and Encapsulation are the other concepts that OOPs features.


Object
An Object is a representation of some real-world thing (i.e person, place) or event. Objects can have both attributes and behaviors.

Class
A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

Main OOPS Concepts are Encapsulation, Abstraction, Inheritance and Polymorphism.

1) Encapsulation: Wrapping up of data and methods in to a single unit is called as encapsulation.
     A car is can be used as a example for Encapsulation. Because it protected some unwanted parts or functions to user.

2) Abstraction: This will be explained with an example for easier understanding.
     Even without the hardware knowledge you can e-mail or do other jobs on the computer. Or a person diving a car should not necessary to know how the engine works.


3) Inheritance: Process of acquiring properties from one object to another without changes. It is the process by which one object acquires the properties of another object.
    For example. Son will aquire the behaviours from his father.

4) Polymorphism: Process of acquiring properties from one object to another with changes.
    poly=many
    morphism=forms

There are two types of polymorphisms.
1.Compile-time polymorphism: what object will be assigned to the present variable. This will be evaluated at compile time.
This is known as compile-time polymorphism.
2.Run-time polymorphism:what object will be assigned to the present variable. This will be evaluated at runtime depending
on condition. This is known as Run-time polymorphism.

How this be used in a program is explained below using a simple example.

String getTaste(Fruit fruit){
      //this method will return the taste of the fruit regarding the argument
}
 
We can dynamically(in runtime) get the "taste of fruit" as per the change in argument.

getTaste(apple);
getTaste(lemon);

Here the argument object changes, but the call is going into the same method.


Architectural benefits of Spring



Some of the benefits Spring can bring to a project:
  • Spring can effectively organize your middle tier objects, whether or not you choose to use EJB. Spring takes care of plumbing that would be left up to you if you use only Struts or other frameworks geared to particular J2EE APIs.
  • Spring can eliminate the proliferation of Singletons seen on many projects. 
  • Spring can eliminate the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. The use of Inversion of Control and Dependency Injection helps achieve this simplification.
  • Spring can facilitate good programming practice by reducing the cost of programming to interfaces, rather than classes, almost to zero.
  • Spring is designed so that applications built with it depend on as few of its APIs as possible. Most business objects in Spring applications have no dependency on Spring.
  • Applications built using Spring are very easy to unit test.
  • Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code.
  • Spring helps you solve many problems without using EJB. Spring can provide an alternative to EJB that's appropriate for many applications. For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA implementation, if you only need to work with a single database.
Spring is essentially a technology dedicated to enabling you to build applications using POJOs. This desirable goal requires a sophisticated framework, which conceals much complexity from the developer.

Exceptions in java

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.

A Program Showing How the JVM throws an Exception at runtime

public class DivideException {

    public static void main(String[] args) {
     division(100,4);  // Line 1
     division(100,0);        // Line 2
        System.out.println("Exit main().");
    }

    public static void division(int totalSum, int totalNumber) {

     System.out.println("Computing Division.");
     int average  = totalSum/totalNumber;
        System.out.println("Average : "+ average);
    }
}


An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method.

Output
Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)

Exception in thread “main”

Exceptions in Java

Throwable Class 

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

Syntax:

String getMessage()
void printStackTrace()
String toString()

Class Exception
The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException
Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

Class Error
Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller.

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax:
Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}

try Block
The java code that you think may produce an exception is placed within a try block for a suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed.

catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception).

finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

The following program illustrates the scenario.


try {
    <code>
} catch (<exception type1> <parameter1>) { // 0 or more
    <statements>

}
} finally {                               // finally block
    <statements>
}

Output:
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1

Below is a program showing the Normal Execution of the Program.
Please note that no NullPointerException is generated as was expected by most people

public class DivideException2 {

    public static void main(String[] args) {
     int result  = division(100,0);        // Line 2
        System.out.println("result : "+result);
    }

    public static int division(int totalSum, int totalNumber) {
     int quotient = -1;
     System.out.println("Computing Division.");
     try{
      quotient  = totalSum/totalNumber;

     }
     catch(Exception e){
      System.out.println("Exception : "+ e.getMessage());
     }
     finally{
      if(quotient != -1){
       System.out.println("Finally Block Executes");
       System.out.println("Result : "+ quotient);
      }else{
       System.out.println("Finally Block Executes. Exception Occurred");
       return quotient;
      }

     }
     return quotient;
    }
}

Output
null (And not NullPointerException)

Abstract Class in java


Java 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();
}

Example of a shape class as an abstract class

abstract class Shape {

     public String color;
     public Shape() {
 }
 public void setColor(String c) {
     color = c;
 }
 public String getColor() {
     return color;
 }
 abstract public double area();
}
 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

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.

Example 1: 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.

Example 2: 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



Next : Exceptions in java

Object Reference Type Casting


In java object typecasting one object reference can be type 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.
How to Typecast Objects with a dynamically loaded Class ? - 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 casting java scenarios
· 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 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 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 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 program 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

instanceof Operator

The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the object implements the interface, otherwise it returns false.
Below is an example showing the use of instanceof operator
class Vehicle {

 String name;
 Vehicle() {
  name = "Vehicle";
 }
}

class HeavyVehicle extends Vehicle {

 HeavyVehicle() {
  name = "HeavyVehicle";
 }
}

class Truck extends HeavyVehicle {

 Truck() {
  name = "Truck";
 }
}

class LightVehicle extends Vehicle {

 LightVehicle() {
  name = "LightVehicle";
 }
}

public class InstanceOfExample {

 static boolean result;
 static HeavyVehicle hV = new HeavyVehicle();
 static Truck T = new Truck();
 static HeavyVehicle hv2 = null;
 public static void main(String[] args) {
  result = hV instanceof HeavyVehicle;
  System.out.print("hV is an HeavyVehicle: " + result + "\n");
  result = T instanceof HeavyVehicle;
  System.out.print("T is an HeavyVehicle: " + result + "\n");
  result = hV instanceof Truck;
  System.out.print("hV is a Truck: " + result + "\n");
  result = hv2 instanceof HeavyVehicle;
  System.out.print("hv2 is an HeavyVehicle: " + result + "\n");
  hV = T; //Sucessful Cast form child to parent
  T = (Truck) hV; //Sucessful Explicit Cast form parent to child
 }
}


Output
hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false



Next : Abstract class

Java Inheritance

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box {

 double width;
 double height;
 double depth;
 Box() {
 }
 Box(double w, double h, double d) {
  width = w;
  height = h;
  depth = d;
 }
 void getVolume() {
  System.out.println("Volume is : " + width * height * depth);
 }
}

public class MatchBox extends Box {

 double weight;
 MatchBox() {
 }
 MatchBox(double w, double h, double d, double m) {
  super(w, h, d);

  weight = m;
 }
 public static void main(String args[]) {
  MatchBox mb1 = new MatchBox(10, 10, 10, 10);
  mb1.getVolume();
  System.out.println("width of MatchBox 1 is " + mb1.width);
  System.out.println("height of MatchBox 1 is " + mb1.height);
  System.out.println("depth of MatchBox 1 is " + mb1.depth);
  System.out.println("weight of MatchBox 1 is " + mb1.weight);
 }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0


What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass
class Vehicle {

 // Instance fields
 int noOfTyres; // no of tyres
 private boolean accessories; // check if accessorees present or not
 protected String brand; // Brand of the car
 // Static fields
 private static int counter; // No of Vehicle objects created
 // Constructor
 Vehicle() {
  System.out.println("Constructor of the Super class called");
  noOfTyres = 5;
  accessories = true;
  brand = "X";
  counter++;
 }
 // Instance methods
 public void switchOn() {
  accessories = true;
 }
 public void switchOff() {
  accessories = false;
 }
 public boolean isPresent() {
  return accessories;
 }
 private void getBrand() {
  System.out.println("Vehicle Brand: " + brand);
 }
 // Static methods
 public static void getNoOfVehicles() {
  System.out.println("Number of Vehicles: " + counter);
 }
}

class Car extends Vehicle {

 private int carNo = 10;
 public void printCarInfo() {
  System.out.println("Car number: " + carNo);
  System.out.println("No of Tyres: " + noOfTyres); // Inherited.
  //  System.out.println("accessories: "    + accessories); // Not Inherited.
  System.out.println("accessories: " + isPresent()); // Inherited.
  //        System.out.println("Brand: "     + getBrand());  // Not Inherited.
  System.out.println("Brand: " + brand); // Inherited.
  //  System.out.println("Counter: "    + counter);     // Not Inherited.
  getNoOfVehicles(); // Inherited.
 }
}

public class VehicleDetails { // (3)

 public static void main(String[] args) {
  new Car().printCarInfo();
 }
}
Output
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1


this and super keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.
class Counter {

 int i = 0;
 Counter increment() {
  i++;
  return this;
 }
 void print() {
  System.out.println("i = " + i);
 }
}

public class CounterDemo extends Counter {

 public static void main(String[] args) {
  Counter x = new Counter();
  x.increment().increment().increment().print();
 }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Next : Object reference type casting

Introduction to Object Serialization


Java object serialization is used to persist Java objects to a file, database, network, process or any other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then be read at a later time, or in another environment, to recreate the original objects.
Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.
public interface Serializable
  • The Serializable interface has no methods or fields. (Marker Interface)
  • Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

Transient Fields and Java Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization.
You can use the transient keyword to describe temporary variables, or variables that contain local information,


such as a process ID or a time lapse.

Input and Output Object Streams

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface for deserializing objects.
These high-level streams are each chained to a low-level stream, such as FileInputStream or FileOutputStream.
The low-level streams handle the bytes of data. The writeObject method saves the state of the class by writing the individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
the object input stream.
Case 1: Below is an example that demonstrates object Serialization into a File
PersonDetails is the bean class that implements the Serializable interface
import java.io.Serializable;
public class PersonDetails implements Serializable {

 private String name;
 private int age;
 private String sex;
 public PersonDetails(String name, int age, String sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
}
GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails {

 public static void main(String[] args) {
  String filename = "person.txt";
  List pDetails = null;
  FileInputStream fis = null;
  ObjectInputStream in = null;
  try {
   fis = new FileInputStream(filename);
   in = new ObjectInputStream(fis);
   pDetails = (ArrayList) in.readObject();
   in.close();
  } catch (IOException ex) {
   ex.printStackTrace();
  } catch (ClassNotFoundException ex) {
   ex.printStackTrace();
  }
  // print out the size
  System.out.println("Person Details Size: " + pDetails.size());
  System.out.println();
 }
}
PersonPersist is the class that is used to serialize object into the File (person.txt).
public class PersonPersist {

 public static void main(String[] args) {
  String filename = "person.txt";
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  List list = new ArrayList();
  list.add(person1);
  list.add(person2);
  list.add(person3);
  FileOutputStream fos = null;
  ObjectOutputStream out = null;
  try {
   fos = new FileOutputStream(filename);
   out = new ObjectOutputStream(fos);
   out.writeObject(list);
   out.close();
   System.out.println("Object Persisted");
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }
}
——————————————————————————–
Case 2: Below is an example that demonstrates object Serialization into the database
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
Create SerialTest Table
create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);
PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

 static String userid = "scott", password = "tiger";
 static String url = "jdbc:odbc:bob";
 static int count = 0;
 static Connection con = null;
 public static void main(String[] args) {
  Connection con = getOracleJDBCConnection();
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  PreparedStatement ps;
  try {
   ps = con
     .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
   write(person1, ps);
   ps.execute();
   write(person2, ps);
   ps.execute();
   write(person3, ps);
   ps.execute();
   ps.close();
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
   while (rs.next()) {
    Object obj = read(rs, "Name");
    PersonDetails p = (PersonDetails) obj;
    System.out.println(p.getName() + "\t" + p.getAge() + "\t"
      + p.getSex());
   }
   rs.close();
   st.close();
  } catch (Exception e) {
  }
 }
 public static void write(Object obj, PreparedStatement ps)
   throws SQLException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oout = new ObjectOutputStream(baos);
  oout.writeObject(obj);
  oout.close();
  ps.setBytes(1, baos.toByteArray());
  ps.setInt(2, ++count);
 }
 public static Object read(ResultSet rs, String column)
   throws SQLException, IOException, ClassNotFoundException {
  byte[] buf = rs.getBytes(column);
  if (buf != null) {
   ObjectInputStream objectIn = new ObjectInputStream(
     new ByteArrayInputStream(buf));
   return objectIn.readObject();
  }
  return null;
 }
 public static Connection getOracleJDBCConnection() {
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  } catch (java.lang.ClassNotFoundException e) {
   System.err.print("ClassNotFoundException: ");
   System.err.println(e.getMessage());
  }
  try {
   con = DriverManager.getConnection(url, userid, password);
  } catch (SQLException ex) {
   System.err.println("SQLException: " + ex.getMessage());
  }
  return con;
 }
}
——————————————————————————–
Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
Create SerialTest Table
create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);
PersonPersist is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

 static String userid = "scott", password = "tiger";
 static String url = "jdbc:odbc:bob";
 static int count = 0;
 static Connection con = null;
 static String s;
 public static void main(String[] args) {
  Connection con = getOracleJDBCConnection();
  PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
  PersonDetails person2 = new PersonDetails("bob", 12, "Male");
  PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
  PreparedStatement ps;
  try {
   ps = con
     .prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
   write(person1, ps);
   ps.execute();
   write(person2, ps);
   ps.execute();
   write(person3, ps);
   ps.execute();
   ps.close();
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
   while (rs.next()) {
    Object obj = read(rs, "Name");
    PersonDetails p = (PersonDetails) obj;
    System.out.println(p.getName() + "\t" + p.getAge() + "\t"
      + p.getSex());
   }
   rs.close();
   st.close();
  } catch (Exception e) {
  }
 }
 public static void write(Object obj, PreparedStatement ps)
   throws SQLException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oout = new ObjectOutputStream(baos);
  oout.writeObject(obj);
  oout.close();
  byte[] buf = baos.toByteArray();
  s = new sun.misc.BASE64Encoder().encode(buf);
  ps.setString(1, s);
  // ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));
  ps.setBytes(1, baos.toByteArray());
  ps.setInt(2, ++count);
 }
 public static Object read(ResultSet rs, String column)
   throws SQLException, IOException, ClassNotFoundException {
  byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s);
  // byte[] buf = Base64.base64ToByteArray(new
  // String(rs.getBytes(column)));
  if (buf != null) {
   ObjectInputStream objectIn = new ObjectInputStream(
     new ByteArrayInputStream(buf));
   Object obj = objectIn.readObject(); // Contains the object
   PersonDetails p = (PersonDetails) obj;
   System.out.println(p.getName() + "\t" + p.getAge() + "\t"
     + p.getSex());
  }
  return null;
 }
 public static Connection getOracleJDBCConnection() {
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  } catch (java.lang.ClassNotFoundException e) {
   System.err.print("ClassNotFoundException: ");
   System.err.println(e.getMessage());
  }
  try {
   con = DriverManager.getConnection(url, userid, password);
  } catch (SQLException ex) {
   System.err.println("SQLException: " + ex.getMessage());
  }
  return con;
 }
}
Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before theobject to be serialized must implement the Serializable interface. PersonDetails is the bean class that implements the Serializable interface
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectSerializationExample {

 public static void main(String args[]) {
  try {
   Object object = new javax.swing.JButton("Submit");
   // Serialize to a file namely "filename.dat"
   ObjectOutput out = new ObjectOutputStream(
     new FileOutputStream("filename.dat"));
   out.writeObject(object);
   out.close();
   // Serialize to a byte array
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   out = new ObjectOutputStream(bos);
   out.writeObject(object);
   out.close();
   // Get the bytes of the serialized object
   byte[] buf = bos.toByteArray();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
 
 
Next: Java Inheritance 
 
 
 

Java constructor

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube1() {
  length = 10;
  breadth = 10;
  height = 10;
 }
 Cube1(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
 }
 public static void main(String[] args) {
  Cube1 cubeObj1, cubeObj2;
  cubeObj1 = new Cube1();
  cubeObj2 = new Cube1(10, 20, 30);

  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
 }
}



Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Java Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context
public class Cube2 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube2() {
  this(10, 10);
  System.out.println("Finished with Default Constructor");
 }
 Cube2(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having 2 params");
 }
 Cube2(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having 3 params");
 }
 public static void main(String[] args) {
  Cube2 cubeObj1, cubeObj2;
  cubeObj1 = new Cube2();
  cubeObj2 = new Cube2(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
 }
}

public class Cube2 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube2() {
  this(10, 10);
  System.out.println("Finished with Default Constructor");
 }
 Cube2(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having 2 params");
 }
 Cube2(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having 3 params");
 }
 public static void main(String[] args) {
  Cube2 cubeObj1, cubeObj2;
  cubeObj1 = new Cube2();
  cubeObj2 = new Cube2(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
 }
}

Output

Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000


Next : Introduction to object serialization


Introduction to Java Classes



A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.
A class has the following general syntax:
<class modifiers>class<class name>
<extends clause> <implements clause>
{

// Dealing with Classes (Class body)

<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().
public class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
}
How do you reference a data member/function?
This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).
For example:
cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.
Consider this simple Java program showing the use of static fields and static methods
// Class and Object initialization showing the Object Oriented concepts in Java
class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public static int numOfCubes = 0; // static variable
 public static int getNoOfCubes() { //static method
  return numOfCubes;
 }
 public Cube() {
  numOfCubes++; //
 }
}

public class CubeStaticTest {

 public static void main(String args[]) {
  System.out.println("Number of Cube objects = " + Cube.numOfCubes);
  System.out.println("Number of Cube objects = "
    + Cube.getNoOfCubes());
 }
}

Output
Number of Cube objects = 0
Number of Cube objects = 0

Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.
Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Introduction to Java Objects

The Object Class is the super class for all classes in Java.
Some of the object class methods are

equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.
Below is an example showing the creation of Cube objects by using the new operator.
public class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public int getVolume() {
  return (length * breadth * height);
 }
 public static void main(String[] args) {
  Cube cubeObj; // Creates a Cube Reference
  cubeObj = new Cube(); // Creates an Object of Cube
  System.out.println("Volume of Cube is : " + cubeObj.getVolume());
 }
}

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading

public class MethodOverloadDemo {

 void sumOfParams() { // First Version
  System.out.println("No parameters");
 }
 void sumOfParams(int a) { // Second Version
  System.out.println("One parameter: " + a);
 }
 int sumOfParams(int a, int b) { // Third Version
  System.out.println("Two parameters: " + a + " , " + b);
  return a + b;
 }
 double sumOfParams(double a, double b) { // Fourth Version
  System.out.println("Two double parameters: " + a + " , " + b);
  return a + b;
 }
 public static void main(String args[]) {
  MethodOverloadDemo moDemo = new MethodOverloadDemo();
  int intResult;
  double doubleResult;
  moDemo.sumOfParams();
  System.out.println();
  moDemo.sumOfParams(2);
  System.out.println();
  intResult = moDemo.sumOfParams(10, 20);
  System.out.println("Sum is  " + intResult);
  System.out.println();
  doubleResult = moDemo.sumOfParams(1.1, 2.2);
  System.out.println("Sum is  " + doubleResult);
  System.out.println();
 }
}


Output
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003
Below is a code snippet to shows the interfaces that a Class Implements:
Class cls = java.lang.String.class;
Class[] intfs = cls.getInterfaces();
// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]
// The interfaces for a primitive type is an empty array
cls = int.class;
intfs = cls.getInterfaces(); // []
Below is a code snippet to show whether a Class Object Represents a Class or Interface:
Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false
 
 
 
 
 
 Next : Java constructor
 

Multicasting



What is multi cast.
Muticast in a datagram network is the transmission of the data packet to a subset of hosts.
The basic benefit of multicast is that any source can send down its data to required destination, which is not a single host but can be a group of hosts sharing a common address. So the sender sees the destination as a single host. Hence the duty of sender is completed, once it sends a single data packet destined to the abstract group. Even the intermediate routers have no idea regarding the exact set of hosts.
If multicast was not supposed to be used, then source has to send the data packets one for each host. Moreover multicast encapsulates the actual hosts.
The destination host should subscribe to receive the messages from a source to that group. The host can unsubscribe whenever it intends to do so.

Multicasting in Java

Sending multicast datagrams

In order to send any kind of datagram in Java, be it unicast, broadcast or multicast, one needs a java.net.DatagramSocket:
DatagramSocket socket = new DatagramSocket();
One can optionally supply a local port to the DatagramSocket constructor to which the socket must bind. This is only necessary if one needs other parties to be able to reach us at a specific port. A third constructor takes the local port AND the local IP address to which to bind. This is used (rarely) with multi-homed hosts where it is important on which network adapter the traffic is received. Neither of these is necessary for this example.
This sample code creates the socket and a datagram to send and then simply sends the same datagram every second:
DatagramSocket socket = new DatagramSocket();

byte[] b = new byte[DGRAM_LENGTH];
DatagramPacket dgram;

dgram = new DatagramPacket(b, b.length,
InetAddress.getByName(MCAST_ADDR), DEST_PORT);

System.err.println("Sending " + b.length + " bytes to " +
dgram.getAddress() + ':' + dgram.getPort());
while(true) {
System.err.print(".");
socket.send(dgram);
Thread.sleep(1000);
}
Valid values for the constants are:
  • DGRAM_LENGTH: anything from 0 to 65507 , eg 32
  • MCAST_ADDR: any class D address , eg 235.1.1.1
  • DEST_PORT: an unsigned 16-bit integer, eg. 7777
It is important to note the following points:
    1. DatagramPacket does not make a copy of the byte-array given to it, so any change to the byte-array before the socket.send() will reflect in the data actually sent;
    2. One can send the same DatagramPacket to several different destinations by changing the address and or port using the setAddress() and setPort() methods;
    3. One can send different data to the same destination by changing the byte array referred to using setData() and setLength() or by changing the contents of the byte array the DatagramPacket is referring to;
    4. One can send a subset of the data in the byte array by manipulating offset and length through the setOffset() and setLength() methods.

Receiving multicast datagrams

One can use a normal DatagramSocket to send and receive unicast and broadcast datagrams and to send multicast datagrams as seen in the section 2. In order to receive multicast datagrams, however, one needs a MulticastSocket. The reason for this is simple, additional work needs to be done to control and receive multicast traffic by all the protocol layers below UDP.
The example given below, opens a multicast socket, binds it to a specific port and joins a specific multicast group:
byte[] b = new byte[BUFFER_LENGTH];
DatagramPacket dgram = new DatagramPacket(b, b.length);
MulticastSocket socket =
new MulticastSocket(DEST_PORT); // must bind receive side
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));

while(true) {
socket.receive(dgram); // blocks until a datagram is received
System.err.println("Received " + dgram.getLength() +
" bytes from " + dgram.getAddress());
dgram.setLength(b.length); // must reset length field!
}
Values for DEST_PORT and MCAST_ADDR must match those in the sending code for the listener to receive the datagrams sent there. BUFFER_LENGTH should be at least as long as the data we intend to receive. If BUFFER_LENGTH is shorter, the data will be truncated silently and dgram.getLength() will return b.length.
The MulticastSocket.joinGroup() method causes the lower protocol layers to be informed that we are interested in multicast traffic to a particular group address. One may execute joinGroup() many times to subscribe to different groups. If multiple MulticastSockets bind to the same port and join the same multicast group, they will all receive copies of multicast traffic sent to that group/port.
As with the sending side, one can re-use ones DatagramPacket and byte-array instances. The receive() method sets length to the amount of data received, so remember to reset the length field in the DatagramPacket before subsequent receives, otherwise you will be silently truncating all your incoming data to the length of the shortest datagram previously received.
One can set a timeout on the receive() operation using socket.setSoTimeout(timeoutInMilliseconds). If the timeout is reached before a datagram is received, the receive() throws a java.io.InterruptedIOException. The socket is still valid and usable for sending and receiving if this happens. 



 

Most Reading

Stats