Saturday, September 21

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


-->

Friday, September 20

Java concurrency interrupt method theory , wating thread and interruptException

             Java concurrency interrupt method theory ,  wating thread and interruptException


java Thread interrupt method

one important thing to know about this method  :

This method throws interruption exception only for waiting thread .

If thread is not in waiting status thread's interrupted status will be set to true but it won't stop it's execution there instead thread will continue running normally

For example

class MyThread extends Thread {


public void run(){

try{
Thread.currentThread().sleep(100);

for (int i=0;i<100 br="" i="">System.out.println(i);
}
}catch(InterruptedException exp){
    System.out.println(1);
exp.getMessage();
}
 }

}

public class Test{

public static void main(String args[]){

Thread t=new MyThread();

t.start();
t.interrupt();

}
}
In above example when t.interrupt() method is invoked Mythread thread is in sleeping i.e. waiting status . So it would be interrupted and for loop won't be executed but execution control flow will land up directly in catch block .








Now let's change this scenario a bit


class MyThread extends Thread {


public void run(){

try{
Thread.currentThread().sleep(101);

for (int i=0;i<100 br="" i="">System.out.println(i);
}
}catch(InterruptedException exp){
    System.out.println(1);
exp.getMessage();
}
 }

}

public class Test{

public static void main(String args[]){

Thread t=new MyThread();

t.start();
try {
    Thread.sleep(101);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
t.interrupt();

}


Here after starting the thread , t.interrupt() is not invoked immediately but after waiting for 101 ms . So , here when t.interrupt() in invoked MyThread thread has already come out of sleeping status. So it won't be interrupted and for loop will be executed normally without any exception.


Thus interrupt() method will cause interruptException only when invoked thread is in waiting status .

 

What are the different way , a thread can go in waiting status is listed here


-->




java.lang.Thread.interrupted() method oncoked twice ..

                            java.lang.Thread.interrupted() method oncoked twice ..




If java.lang.Thread.interrupted() method is invoked twice , In second execution it will always return true.

Why?

Thread.interrupted() method does two things

1. returns the current status
2. clears the interrupted flag . i.e. set the interrupted flag of thread to false.


So at the time of first execution what ever might be the status of interruption flag of thread , it will follow above tow steps

1. return current status (true or false i.e. interrupted or not-interrupted)
2. clears the interrupted flag . i.e. set the interrupted flag of thread to fa
lse.

And at the time of second execution , as status after first execution is already set to false So

1. return current status (false)
2. clears the interrupted flag . i.e. set the interrupted flag of thread to false.

Thus is case of two successive execution of Thread.interrupted() method second execution will always return false.


So What is the purpose of Thread.interrupted() method at all in java




Sole purpose is to know the current interruption status of thread and also clearing the interruption status.







methods that take a thread to waiting status

                                              methods that take a thread to waiting status

-->





Methods in java concurrency when threads come in waiting status


  1. Thread.sleep() 
  2. BlockingQueue.get()
  3. Semaphore.acquire();
  4. wait();
  5. join();


-->








-->

Java Reflection API , Refection advantages in java , Java Refection introspection basics.

Java Reflection API , Refection advantages in java , Java Refection introspection basics.




                                                                  Java Refection API

Refection is useful where to don't want to write a logic repeatedly many times for similar kind of object structure creation .

Reflection will reduce the overall code drastically and help in maintaining a generic code for multiple modules.

Refection directly operates on java meta data , Meta data of class like class name , constructor , methods , variable and thus provide a generic way of writing logic for multiple similar object structures

Refection provide you capability of introspecting and invoking operations by searching the suitable method at run-time.

For Example :

public class JavaReflection{


public static void PrintClassDetailsObject obj)

 Class type = obj.getClass();
 final Method[] methods = type.getMethods();

if(type instanceOf Politician)
foreach (Method method: methods )
if(method.equalsIgnorecase(ContentElection)

method();

)

if(type instanceOf Doctor
foreach (Method method: methods )
if(method.equalsIgnorecaseoperatePatient

method();

)

if(type instanceOf Actor
foreach (Method method: methods )
if(method.equalsIgnorecase(playRole)

method();

)
}
As illustrated in above example at run-time It is being identified which class does the object belongs to and depending upon that a specific method is searched out. If method is available then required operation is performed. There are lot of If ,else conditions but good thing is that we are not writing there different classes to handle different sent of features .


So if there are 1000 variations of the above implementation all can be easily plugged in here .So you are writing little code catering to wide range of features and introducing generic behavior which further makes it extensible with very little extra code and effort As the basic structure and design for any similar enhancement is already in place. No further investment of design for enhancement of similar nature But Just the core implementation effort. 

Refection class here is creating an execution blueprint . It does not have feature specific logic or code But in certain cases this kind of implementation is useful when we want to provide a centralized control of routing the request to different classes.



Reflection also has got the capability of handling overloaded methods. At run-time we can check parameters passed along with the method name to resolve the exact method .

For example :

 for (int idx = 0; idx < methods.length; idx++) {
     if (methods[idx].getName() .startsWith"PLAY"{
 if (methods[idx].getParameterTypes()[0] == String.class) {
 methods[idx].invoke(obj, new Object[] { new String() }
);
}}










Top 3 most used classes of Refection API in java


1. Class java.lang.reflect.Method

 
This class contains a description of a method and the means to dynamically invoke
it. You can use instances of this class to dynamically invoke methods.


2. Class java.lang.reflect.Modifier


  Using Modifier , you can determine whether a field is public,private,static,transient , and so on.

3. Class java.lang.reflect.AccessibleObject

 It allows you to bypass class access constraints such as “private,” which allows you to
execute methods and set fields that would normally be blocked by visibility specifiers. Visibility of private fields can be modified to make it accessible at run-time.