Sunday, September 22

Java Polymorpihsm , OOPS design principal , Dynamic binding , Overriding

                   Java Polymorpihsm , OOPS design principal , Dynamic binding , Overriding





What is polymorphism?

Ability of an java object to take more than one form is polymorphism.

What does that mean?

Let's take an practical example to understand this 

Say we have an living being called animal  who is a horse .Now I can say

Horse is running  

 OR
Animal is running


both are correct .Thus single living being is taking two form here


 1)Horse 2)Animal

Let's understand this by code

public class Animal{

}

public class Horse extends Animal{
}

public class Race {

public static void main(String args[]){

//here we can write

Animal animal =new Animal();

//as well as

Horse animal =new Horse();
Animal animal =new Horse();

}

}
So animal reference in above example is representing both Animal as well as Horse . Both are correct.

So animal reference of Animal class is taking more than one actual form here . This is polymorphism . Polymorphism is widely used in java and OO programming.Parent class or implemented interface reference is used to refer the subclass instance.


So is there any direct way to identify If an reference is polymorphic or not ?

There is straight formula to identify that

If a object pass more than one IS A relationship , It is polymorphic.


Horse animal =new Horse();
Animal animal =new Horse();


Horse instance above can be represented with Horse class reference as well as Animal class reference . Thus horse instance here depicts the polymorphic behavior.

Lets take another example :

public interface Politician{}
public class Minister{}
public class FinanceMinister extends Minister implements Politician{}
Now, the FinanceMinister class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:

  1.     A FinanceMinister IS-A Minister
  2.     A FinanceMinister IS-A Politician
  3.     A FinanceMinister IS-A FinanceMinister
  4.     A FinanceMinister IS-A Object

SO all below declarations are correct


FinanceMinister fm = new FinanceMinister ();
Minister m = fm;
Politician p = fm;
Object o = fm



All the reference variables fm,m,p,o refer to the same FinanceMinister object in the heap.;



-->



Polymorphism is extensively used in other OO concept overriding.

For example :


public class Politician {

void contest(){
}

}

public class Candidate extends Politician {

void contest(){
}

}

public class Election {


public static void main (String args[])
{

Politician polit=new Candidate()

Candidate polit1=new Candidate();

polit.contest();
polit1.contest();

}
}
Both method invocation polit.contest() and polit1.contest() invoke the contest method of Candidate Class .

Why?

because Candidate class is depicting polymorphic behavior here

It can be referred by Candidate class reference as well as Politician class reference and also Object class reference.

Although compiler looks for contest() method in both the classes separately for both statements to compile successfully. But at run-time It is decided based on the instance type , method of which class should be called.

Both reference refer to the instance of Candidate class so JVM invokes method of Candidate class in both the cases .

Thus polymorphism helps in achieving dynamic behavior at run-time.













Saturday, September 21

Marker interface , Cloneable, serializable,Eventlistener,Remote,RandomAccess,EnterpriseBean

Marker interface , Cloneable, serializable,Eventlistener,Remote,RandomAccess,EnterpriseBean




Marker Interfaces are give about the implementing classes.


Interface in java defines a specific behavior while class can define both behavior and state. So Interface is pure behavior and class represent state and behavior. Interfaces are used in Java to specify the behavior of classes that implement those interfaces.. interfaces in Java that have no behavior  are known as marker interfaces. They have no method defined in them but are absolutely empty.



-->


examples of marker interfaces

Java.lang.Cloneable
If you want to added cloneable feature in a class ,that class needs to implement Cloneable interface.

java.io.Serializable Serialization is nothing but s saving the state of an object to persistent storage as byte stream. Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized.  The serialization interface has no methods or fields .

java.util.EventListener
A tagging interface that all event listener interfaces must extend.

java.rmi.Remote
The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object  implements this interface.

Javax.servlet.SingleThreadModel
Ensures that servlets handle only one request at a time. This interface has no methods. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method.

Java.util.RandomAccess
This Marker interface used by classes implementing List interface to  support fast random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.

Javax.ejb.EnterpriseBean
The EnterpriseBean interface must be implemented by every enterprise Bean class. It is a common superinterface for the SessionBean, EntityBean and MessageDrivenBean interfaces.


Reference From Sun Documentation







8 reasons Why Object Pooling is recommended , connection pooling , threadpooling.

    8 reasons Why Object Pooling is recommended , connection pooling , threadpooling.




1. Performance

Object pooling provides better application performance As object creation is not done when client actually need it to perform some operation on it Instead objects are already created in the pool and readily available to perform any time. So Object creation activity is done much before So it does help in achieving better run-time performance

2. Object sharing :

Object Pooling encourage the concept of sharing. Objects available in pool can be shared among multiple worker threads . One thread Use the Object and once used it returns back to its Object pool and then it can be used by some other worker thread. So once created objects are not destroyed and thus destruction and creation again and again is not required. That again help in generating better performing code.

3. Control on Object instances :

 By declaring size of Object pool we can control the no of instance creation. Thus a finite no of objects are created as decided depending upon required application capacity and scalability or peak load.

4. Memory conservation : 

Finite no of instances are created So it helps in better memory management . Too many instances are not unnecessary created Instead a finite no of instances available in pool serve to all working threads . Creating a new instance for every worker thread can be too expensive than to restrict the instance pool size to a finite number and let the worker thread wait for a while if all Object pool instances are under use when instance is requested by worker thread.


-->


5. Garbage Collection Friendly

Objects created in pool are not frequently destroyed and created so garbage collector does not need to continuously track them for their reach-ability. Thus there is no burden of considering these instances in every garbage collection .

6. Wide Application container support. Application server provides excellent support to maintain and manage the object pool For example Database connection pool by defining data-source for database and configuring the same in server configurations. Thus developer has to write no code to manage the instance pool . And security , transaction , resource management all are application server's responsibility. Developer can concentrate on core logic and can rely on application server for Instance pooling cross cutting concern

7. Centralized and uncluttered code . 

That help in better manageability and maintainability . Also Object pooling configuration properties for example pool size can be externalized So with varying application load pool capacity can be externally increased or decreased without requiring any code build and deployment.

8. early detection of service down issue.

  If database service is down It can be monitored early when instances in pool are created instead of when any client actually need that Object . Thus some corrective or alternative measures can be taken before client hit the server and ask for an object from object pool.












Adding a post to blogger using Google API

                                     Adding a post to blogger using Google API






 How to create a post on blogger using Google API.

Google API jar file required : gdata-core1.0.jar  . Download this jar and add to the class library.





-->

A sample Code here...

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.ServiceException;

import java.io.IOException;
import java.net.URL;

public class Blogger{

    public static void createPost(GoogleService myService) throws ServiceException, IOException {

         // Create the entry to insert
        Entry myEntry = new Entry();


// POST Title
        myEntry.setTitle(new PlainTextConstruct("INDIA DEFEATED PAKISTAN "));


// Post description
        myEntry.setContent(new PlainTextConstruct("INDIA Defeated pakistan in only 4 seconds . Hindustan Jindabad "));




// Blogger URL


        URL postUrl = new URL("http://allindiatelevision.blogspot.in");
 
         myService.insert(postUrl, myEntry);

    }

    public static void main(String ar[]) throws ServiceException, IOException {


//creating Google service required to access and update Blogger post
        GoogleService myService = new GoogleService("blogger", "http://allindiatelevision.blogspot.in/");
        myService.setUserCredentials("gmail username", "password");

        createPost(myService );
    }

}






Method Overriding VS Method Hiding in java





                                  Method Overriding VS Method Hiding in java



If and instance  method in a subclass has same signature  and return type as instance method in the superclass ,it is called overriding.Method signature means name, and the number and the type of its parameters. Number ,type of the parameters should be same in method written in super class and sub class.

 overriding method can also return a subtype of the type returned by the super class method. This is called a co-variant return type.
Foe example

public class Animal {
  
    public void test() {
       
 }
}




public class Dog extends Animal {
   
    public void test() {
    }

}
test() method in Dog class is overridden .

If a  class method in subclass has the same signature as a class method in the superclass, This is called method hiding.

For example

public class Animal {
    public static void test() {
       ;
    }
  
}


public class Dog extends Animal {
    public static void test() {
      
    }
   }
here test() method in Dog class hides test() method of Animal superclass




In case of overriding method defined in subclass is invoked If object of subclass is created and assigned to a reference of superclass or subclass .i.e. if instance of Dog class is assigned to a reference of Dog class or animal class and test() method is invoked ,method written in Dog class will be invoked









 The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. I.e. If reference is of Animal class animal class test() method would be invoked but if reference is of Dog class , Dog class test() method would be invoked.

Lets take another example :

public class Animal {
    public static void testClass() {
        System.out.println("Animal---> Class Method.");
    }
    public void testInstance() {
        System.out.println("Animal---> Instance method.");
    }
}



public class Dog extends Animal {
    public static void testClass() {
        System.out.println("Dog------> class metohd");
    }
    public void testInstance() {
        System.out.println("Dog---->Instance method.");
    }

    public static void main(String[] args) {
        Dog myCat = new Dog();
        Animal animal = lazyDog;
        Animal.testClassMethod();
        animal.testInstanceMethod();
    }
}

The Dog class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Dog and calls testClass() on the class and testInstance() on the instance.

The output from this program is as follows:

Animal---> Class Method
Dog---->Instance method.






Conclusion
So class method invocation depends upon the reference type while instance method invocation depends upon the type of instance created. Method hiding happens for static methods and method overriding for instance methods


-->