Saturday, March 16, 2013

How to rotate ListView Items in Android

This one is really the sexiest animations i have implemented.I needed to rotate the items of the list view on the x-axis 360 degrees.Honestly speaking i search over the net and found a sample which was doing the animation but that was using LayoutAnimationController which rotates the items one by one they are added to the listView.But I had to rotate the items simultaneously.So i used of the code which i used for another ListView Animation that i ll post here soon.

                  Have a look at code here which is self explanatory.


Here is the Layout file containing ListView : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/refresh"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:text="refresh" />

<ListView
    android:id = "@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  
    />
</LinearLayout>
------------------------------------------------------------------------------------------------------------------------------------
Here is the Activity Class having logic for rotation :
package com.example.rotatelistitems;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.AccelerateInterpolator;

import android.view.animation.Animation;

import android.view.animation.AnimationSet;

import android.view.animation.LayoutAnimationController;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.ListView;

public class MainActivity extends Activity implements Runnable {

    String[] items={"India", "America", "Pakistan", "Afganistan", "Srilanka",

               "Paris", "London", "Australia", "Switzerland", "China",

               "Japan", "Malasiya", "Singapore", "Thailand", "Italy",

               "Russia", "Ukraine", "Germany", "Canada"};

   

        Button refresh ;

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            final ListView flightlist = (ListView)findViewById(R.id.list);

            refresh                =    ( Button )findViewById(R.id.refresh);

            flightlist.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,items));

           

           

            refresh.setOnClickListener(new OnClickListener() {

               

                @Override

                public void onClick(View v) {

                   

                    flightlist.post(MainActivity.this);

                   

                   

                }

            });

                                }

       

     

        private Rotate3dAnimation applyRotation(int position, float start, float end) {

            // Find the center of the container ,here i have hardcoded the values

            final float centerX = 0.0f;//view.getWidth()/2.0f;

            final float centerY = 50.0f;//view.getHeight()/2.0f;

            // Create a new 3D rotation with the supplied parameter

            // The animation listener is used to trigger the next animation

       final Rotate3dAnimation rotation = new Rotate3dAnimation( start , end ,              centerX , centerY , 0.0f , true );

            rotation.setDuration(500);

            rotation.setFillAfter(true);

            rotation.setRepeatCount(3);

            rotation.setInterpolator(new AccelerateInterpolator());

            rotation.setAnimationListener(new DisplayNextView(position));

            return rotation;

        }

     

        private final class DisplayNextView implements Animation.AnimationListener {

            private final int mPosition;

            private DisplayNextView(int position) {

                mPosition = position;

            }

            public void onAnimationStart(Animation animation) {

            }

            public void onAnimationEnd(Animation animation) {

            }

            public void onAnimationRepeat(Animation animation) {

            }

        }

        @Override

        public void run() {

            ListView lv = (ListView) findViewById(R.id.list);

            // here animations start

            int first = lv.getFirstVisiblePosition();

            int last = lv.getLastVisiblePosition();

            for (int k = 0; k < last - first + 1; k++) {

                    View child = lv.getChildAt(k);

                 //   int pos = lv.getPositionForView(child);

                    child.startAnimation(applyRotation(0,0,360));

                

                

            }

           

        }

    }

This one is the custom Animation class for rotating ChildViews of a list
package com.example.rotatelistitems;

import android.graphics.Camera;

import android.graphics.Matrix;

import android.view.animation.Animation;

import android.view.animation.Transformation;

public class Rotate3dAnimation extends Animation {

    private final float mFromDegrees;

    private final float mToDegrees;

    private final float mCenterX;

    private final float mCenterY;

    private final float mDepthZ;

    private final boolean mReverse;

    private Camera mCamera;

   

    public Rotate3dAnimation(float fromDegrees, float toDegrees,

            float centerX, float centerY, float depthZ, boolean reverse) {

        mFromDegrees = fromDegrees;

        mToDegrees = toDegrees;

        mCenterX = centerX;

        mCenterY = centerY;

        mDepthZ = depthZ;

        mReverse = reverse;

    }

    @Override

    public void initialize(int width, int height, int parentWidth, int parentHeight) {

        super.initialize(width, height, parentWidth, parentHeight);

        mCamera = new Camera();

    }

    @Override

    protected void applyTransformation( float interpolatedTime , Transformation t ) {

        final float fromDegrees = mFromDegrees;

        float degrees = fromDegrees + ( ( mToDegrees - fromDegrees ) * interpolatedTime );

        final float centerX = mCenterX;

        final float centerY = mCenterY;

        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();

        if (mReverse) {

            camera.translate( 0.0f , 0.0f , mDepthZ * ( 1.0f - interpolatedTime ) );

        } else {

            camera.translate( 0.0f , 0.0f , mDepthZ * ( 1.0f - interpolatedTime ) );

        }

        camera.rotateX(degrees);

        camera.getMatrix(matrix);

        camera.restore();

        matrix.preTranslate(-centerX, -centerY);

        matrix.postTranslate(centerX, centerY);

    }

}

Change the values and enjoy various behaviour of ListView Animation. Please do comment if you like my post :)

Monday, February 4, 2013

Turn your Face towards Interface and Interact with Abstract


This includes questions related to interfaces and abstract classes,marker interfaces.
 INTERFACE : 
1. Interface in java is declared using keyword interface and it represent a Type like any Class in Java. a reference variable of type interface can point to any implementation of that interface in Java. Its also a good Object oriented design principle to "program for interfaces than implementation" because when you use interface to declare reference variable, method return type or method argument you are flexible enough to accept any future implementation of that interface which could be much better and high performance alternative of current implementation. similarly calling any method on interface doesn't tie you with any particular implementation and you can leverage benefit of better or improved implementation over time. This maintenance aspect of interface is also sought in various software design interview questions in Java.
 2) All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants. We have used both Class and interface for storing application wide constants and advantage of using Interface was that you can implement interface and can directly access constants without referring them with class name which was the case earlier when Class is used for storing Constants. Though after introduction of static imports in Java 5 this approach doesn't offer any benefit over Class approach.
 3) All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. you can not define any concrete method in interface. That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.
 4) In Java its legal for an interface to extend( not implement ) multiple interface.

 MARKER INTERFACE : 
 Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM. This is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked "Why this indication can not be done using a flag inside a class?” this make sense right? Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java. From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

ABSTRACT CLASS:
An abstract class can never be instantiated. Its sole
purpose, mission in life, raison d'ĂȘtre, is to be extended (subclassed). (Note, how-
ever, that you can compile and execute an abstract class, as long as you don't try
Class Declarations and Modifiers
to make an instance of it.) Why make a class if you can't make objects out of it?
Because the class might be just too, well, abstract. For example, imagine you have
a class Car that has generic methods common to all vehicles. But you don't want
anyone actually creating a generic, abstract Car object. How would they initialize its
state? What color would it be? How many seats? Horsepower? All-wheel drive? Or
more importantly, how would it behave? In other words, how would the methods be
implemented?
No, you need programmers to instantiate actual car types such as BMWBoxster
and SubaruOutback. We'll bet the Boxster owner will tell you his car does things
the Subaru can do "only in its dreams." Take a look at the following abstract class:

abstract class Car {
private double price;
private String model;
private String year;
public abstract void goFast();
public abstract void goUpHill();
public abstract void impressNeighbors();
// Additional, important, and serious code goes here

}



DIFFERENCE BETWEEN INTERFACE AND ABSTRACT CLASS:
■ All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
■ All variables defined in an interface must be public, static, and final— in other words, interfaces can declare only constants, not instance variables. Declaring an Interface.
■ Interface methods must not be static.
■ Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
■ An interface can extend one or more other interfaces.
■ An interface cannot extend anything but another interface.
■ An interface cannot implement another interface or class.
■ An interface must be declared with the keyword interface.
■ Interface types can be used polymorphically.
■ Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.







Deciding when to use interface and abstract class?
This is a famous question which is there from the days managed languages avoided multiple inheritance. Mainly C# and Java. They brought a new concept called interface to deal with multiple inheritance. (I don't know whether this is introduced by some other language).From those days a new question entered into almost all the technical interviews related to C#,.net and Java. The question is nothing but "What is the difference between interface and abstract class?" which is covered in almost all interview question answersites.

If the candidate is just out of college and had completed any C# / Java course his answer will be
1 ) Interface is created using the keyword 'interface' and abstract class by 'abstract'
2)  Interface cannot have implementation.Some methods in abstract class can have function body.
'Have you used interface in your academic projects?' will almost make him silent.

The candidate who has got experience in using interfaces will say

  • All the methods in interface needs to be implemented.
  • Interfaces are using to implement contracts for eg WCF contract should be interface decorated with  DataContract attribute.
If he has created interface in any of his programs he will say
  • We cannot declare variables in interface.
  • Interfaces don't allow constructors.
  • Interfaces cannot have static members.
  • There is no need to specify access modifies in interface.
  • Interfaces can inherit from interface only where abstract class can be created from interfaces as well as another class.
More advanced programmers will add some more items
  • Interfaces are used to implement multiple inheritance.
  • Interfaces can be implemented by structures.
  • C# allows us to have 2 methods with same signature in single class provided one method is implemented as explicit interface method.
But if you ask even the advanced programmers "What is the ultimate factor which makes you to create an interface or abstract class?" they will be little confused.ie Forget about multiple inheritance and structures.We don't know whether an entity is going to be used in multiple inheritance scenario or not .Also we don't know whether there needs a common base class method implementation.

The answer is simple.

If an object is related to another object using "Is-A" relationship use abstract class. If the object is related to another as "Can-Be" use interface.

eg: Parrot Is-A Bird.Parrot Can fly.Pigeon is-a Bird and it can also fly.Duck is-a Bird .But it cannot fly.Here Is-A decides the need forabstract base class 'Bird'.'Flyable' is a Can-Be behavior. We cannot say all birds can fly. So the Can-Be behavior translate to interface 'IFlyable' or simply 'Flyable'. It would be more clear if we take the case of a Helicopter. It Can fly.But it is not a Bird.

We can conclude as "Use interface if its a behavior.Abstract class in case of common features."


Project That explains everything:





package com.packageone;

public abstract interface AbstractInterface {

/*Interfaces and their methods are implicitly abstract and adding that modifier makes no difference.Is there other rules that applies with an abstract interface?
No, same rules applies. The method must be implemented by any 
(concrete) implementing class.If abstract is obsolete, why is it included in Java?
 Is there a history for abstract interface?
Interesting question. I dug up the first edition of JLS, 
and even there it says "This modifier is 
obsolete and should not be used in new Java programs".

Okay, digging even further... After hitting numerous broken links, 
I managed to find a copy of 
the original Oak 0.2 Specification (or "manual http://www.devx.com/Java/Article/10686"). 
Quite interesting read I must say, and only 38 pages in total! :-)

 Under Section 5, Interfaces, it provides the following example:
 public interface Storing {
     void freezeDry(Stream s) = 0;
     void reconstitute(Stream s) = 0;
 }

 And in the margin it says
 In the future, the " =0" part of declaring methods in interfaces may go away.=
 Assuming =0 got replaced by the abstract keyword, I suspect that abstract was at some point mandatory for interface methods!*/
}
===============================END OF CLASS==========================

package com.packageone;

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.
 }
===================END OF CLASS================================

package com.packageone;

import com.packagetwo.ExtendStaticAbstract;

public class MainClass {
 
   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
   }
}
=========================END OF CLASS================================

package com.packageone;

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();
   p.volume(3);
  }
  
 @Override
 public double volume(int a) {
 System.out.println("overloaded method in interface");
  return a;
 }
 }
========================END OF CLASS=================================

package com.packageone;

interface Shape {
 
 //only public access modifier is allowed in interface but that has to be initialized
 // by default it is static final too
  public  int a = 1;
  
 // no need to write abstract its by default abstract 
  public abstract double area();
  public double volume();
  public double volume(int a);
 }

=============================END OF CLASS============================

package com.packagetwo;

public class Car extends Vehicle{

 @Override
 boolean hasDiskBrake() {
 System.out.println("Abstract method  hasDisKBrake called");
  
 return true;
 }

 @Override
 int getNoofGears() {
 System.out.println("Abstract method getNoofGears called and the num "+numofGears);
 return numofGears;
 }

 @Override
 public void foo() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void bar() {
  // TODO Auto-generated method stub
  
 }

 @Override
 void someMethod() {
  // TODO Auto-generated method stub
  
 }

}
=============================END OF CLASS============================
package com.packagetwo;

public class ExtendStaticAbstract extends  StaticAbstract.Nested{

 @Override
 void someMethod() {
System.out.println("This the implementation for static abstract method");
  
 }
/*
 * The class which is extending the abstract class which implements 
    the interface has to override 
 * its methods
 * */
 @Override
 public void foo() {
 System.out.println("Method of an interface foo() called");
  
 }

 @Override
 public void bar() {
 System.out.println("Method of an interface bar() called");
  
 }
 
 

}

=========================END OF CLASS================================

package com.packagetwo;
/*
 * Similarly, if an interface inherits more than one method with the same signature, 
 * or if a class implements different interfaces containing a method with the same 
 * signature, there is only one such method. 
 * The implementation of this method is ultimately defined by the 
   class implementing the interfaces, and there is no ambiguity there. 
   If the methods have the same signature but different return types, 
   then one of the return types must be a subtype of all the others, 
   otherwise a compile-time error occurs. The implementation must define a 
   method that returns that common subtype."
 
 *   Justification is below
 */
public interface InterfaceA {
    public int methodA();
    public Number methodB();
    // public int methodC(); // conflicting return type
}

interface InterfaceB {
    public int methodA();
    public Integer methodB();
    // public String methodC(); // conflicting return type
}

 class ImplementationOfAandB implements InterfaceA, InterfaceB {
    public int methodA() {
        return 0;
    }
    public Integer methodB() {
        return null;
    }
    // This would NOT work:
    // public Double methodB() {
    //     return null;
    // }
}
 
 //JUSTIFICATION :
/* In the following two interfaces methodA() is identically defined in terms of 
   parameters (none) and return type (int). The implementation class at the bottom 
   defines a single method with this exact signature. As it complies to both interfaces, 
  you get no problem there - any calls made via a reference of type InterfaceA or 
  InterfaceB will be dispatched to this implementation.The second methodB() is defined as 
  returning any subtype of Number (or Number itself) in InterfaceA. InterfaceB defines 
  methodB() as returning an Integer which is a subtype of Number. The implementation class 
  actually implements the method with Integer, thus complying to the contract of both InterfaceA 
  and InterfaceB. No problem here either. The commented out case of methodB() being implemented 
  as returning a Double however would not work: While it would satisfy the contract of 
  InterfaceA, it would conflict with InterfaceB (which demands an Integer).If InterfaceA and 
  InterfaceB were also specifying (different) contracts for a methodC() (commented out in the example) 
  this would be contradictory and create a compiler error. Implementing both signatures (differing only 
  in return type) is not allowed in Java.
  The above rules would also hold true if were to add any parameters to the methods. For simplicity I kept this out of the example
 */

================================END OF CLASS=========================

package com.packagetwo;

interface InterfaceToBeImplemented {

 void foo();
 void bar();
 
}

======================END OF CLASS===================================

package com.packagetwo;

public class MainClass2 {
 public static void main(String[] args) {
 ExtendStaticAbstract eSA = new ExtendStaticAbstract();
 eSA.someMethod(); //OK
 ExtendStaticAbstract.method1();  // OK
 eSA.method2();                   // Ok
// ExtendStaticAbstract.method2();  // Not allowed
 StaticAbstract.Nested.method1(); //OK
 
 eSA.foo();
 eSA.bar();

 
 Car car = new Car();
 
 car.numofGears=2;// default access modifier of abstract class
 car.b = 3; // protected access modifier of abstract class
 car.color = "red"; // default access modifier of abstract class
 Car.c = 4; // public static  access modifier of abstract class
 
  /*
   * NOTE: you cann't instantiate an abstract class but you can create an anonymous inner class 
   * and use its method  
   */

 Vehicle v = new Vehicle() {
  
  @Override
  boolean hasDiskBrake() {
   // TODO Auto-generated method stub
   return false;
  }
  
  @Override
  int getNoofGears() {
   // TODO Auto-generated method stub
   return 0;
  }

  @Override
  public void foo() {
   // TODO Auto-generated method stub
   
  }

  @Override
  public void bar() {
   // TODO Auto-generated method stub
   
  }

  @Override
  void someMethod() {
   // TODO Auto-generated method stub
   
  }

  
 };
//===================END OF CONCEPT=====================================
 /*
  * NOTE: you cann't instantiate an Interface but you can create 
           an anonymous inner class 
  * and use its method  
  */

 InterfaceToBeImplemented in = new InterfaceToBeImplemented() {
  
  @Override
  public void foo() {
   // TODO Auto-generated method stub
   
  }
  
  @Override
  public void bar() {
   // TODO Auto-generated method stub
   
  }
 };
 
  }
}

===========================END OF CLASS==============================

package com.packagetwo;

public class StaticAbstract {

  // A static abstract class  
    public static abstract class Nested  implements InterfaceToBeImplemented{
     
    //NOTE : while implementing interface it didn't ask to override its declared methods
    //But if StaticAbstract class implemented the interface it would ask to override 
    // its declared methods.
     
        abstract void someMethod();  
        
        public static void method1(){
        System.out.println("This is the implemented static method in abstract static class");
        }
        public void method2(){
        System.out.println("This is the implemented non static method in abstract static class");
        }
    }  
 
}


/*
 * Can abstract class be static ?
 *  you can't. you can't get an Instantce of a abstract class or method. 
    abstract methods are only declared but not implmented. 
  if you use static key word, can you call a method like:
  " public void method(); " without Methods body? 
  so you can do nothing like "ClassName.method()"
 *  
 But you can use below
 * class Outer {  
    // A static abstract class  
    public static abstract class Nested {  
        abstract void someMethod();  
    }  
}
 * */
 
=================================END OF CLASS========================

package com.packagetwo;

abstract  class Vehicle extends StaticAbstract.Nested{

 
  int numofGears;
  String color;
  private int a;
  protected int b;
  public static int c;
  abstract boolean hasDiskBrake();
  abstract int getNoofGears();
  
  
 }
================================END OF CONCEPT======================

Easy but bewildered game of Singleton Pattern and Class


This concept will include all aspects of singleton classes which you never have come across.

  Singleton classes: Singleton pattern is often implemented either using lazy loading or by using double-checked locking, which was not safe and broker in Java 1.4, In short before Java 5 writing Singleton was very difficult and one of the tricky interview question asked on Java interviews, but with introduction of Java memory model in Java 5 and change in volatile variable in Java its possible to write thread-safe singleton using double checked locking. Java 5 also introduced Enum in Java, which is the best choice to implement thread-safe Singleton in Java. Creating simple singleton class:This is one of my favorite method to impelemnt Singleton pattern in Java, Since Singleton instance is static and final variable it initialized when class is first loaded into memeory so creation of instance is inherently thread-safe.
public class A{
   public static A a;

 private A(){
  system.out.println(“Constructor is private ”)
}

public static A getInstance(){
  if( a == null )
  a = new A();

 return a;
}
}
Singleton classes using ENUM- Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. Benifits:
 1) Singleton instance is thread-safe because JVM guarantees that Enum instances are created in thread-safe manner.
/**
* Singleton pattern example using Java Enumj
*
public enum EasySingleton{

 INSTANCE;

}

 2) JVM also guarantee to maintains Singleton status when Singleton class implements Serializable which is still possible without Enum by using readResolve() method but tedious and complicated. Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example
public class A{
 
 //readResolve to prevent another instance of Singleton
    private Object readResolve(){

        return INSTANCE;
    }

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but witn Enum Singleton, Serialization is guarnateed by JVM

Singleton Using double-Check locking:Below code is an example of double checked locking in Singleton pattern, here getInstance() method checks two times to see whether INSTANCE is null or not and that’s why it’s called double checked locking pattern, remember that double checked locking is broker before Java 5 but with the guranteed of volatile variable in Java 5 memory model, it should work perfectly.
 
/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;
 
     private DoubleCheckedLockingSingleton(){}
 
     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}
Interview questions on Singleton pattern: 
1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java? Here they will check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.
Answer: Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.
 2) Can you write code for getInstance() method of a Singleton class in Java? Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.
Answer: Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.
 3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer? This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java
Answer: This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.
 4) What is lazy and early loading of Singleton and how will you implement it? This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.
  Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.
 5) Example of Singleton in standard Java Development Kit? This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of them: Java.lang.Runtime with getRuntime() method Java.awt.Toolkit with getDefaultToolkit() Java.awt.Desktop with getDesktop()
 6) What is double checked locking in Singleton? One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.
Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization. /*code is shown above article on double-check locking*/ Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.
 7) How do you prevent for creating another instance of Singleton using clone() method? This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleto and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.
 8) How do you prevent for creating another instance of Singleton using reflection? Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
 9) How do you prevent for creating another instance of Singleton during serialization? Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranted of that.
 10) When is Singleton not a Singleton in Java? There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible.Here is the link to that article Apart from these questions on Singleton pattern, some of my reader contributer few more questions, which I included here. Thank you guys for your contribution.
 11) Why you should avoid the singleton anti-pattern at all and replace it with DI?
Answer: Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container. Singleton Anti-Pattern: with more and more classes calling getInstance the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).
 12) How many ways you can write Singleton Class in Java?
Answer: I know atleast four ways to implement Singleton pattern in Java 1) Singleton by synchronizing getInstance() method 2) Singleton with public static final field initialized during class loading. 3) Singleton generated by static nested class, also referred as Singleton holder pattern. 4) From Java 5 on-wards using Enums
 13) How to write thread-safe Singleton in Java?
Answer: Thread-Saffe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by classloader. At last few more questions for your practice, contributed by some other topics please contribute for finding out the answers and edit here:
14) Singleton vs Static Class?
15) When to choose Singleton over Static Class?
16) Can you replace Singleton with Static Class in Java?
17) Difference between Singleton and Static Class in java?
18) Advantage of Singleton over Static Class?
 19. Since Singleton class has private constructor, can the class be extended? my answer: Since the constructor is private, it can not be extended Follow up question
20. Since it can not be extended is it a final class?
  my answer: yes, it is a final class. not sure about this answer needs discussion so be careful. Strictly speaking, non-final classes with private constructors can be extended using inner classes inside them (provided you're allowed to make changes to the source code):
 
 public class Singleton {
 private Singleton() {
     System.out.println("Singleton ctor");
 }

 public static synchronized Singleton getInstance() {
     if (_instance == null) {
         _instance = new Singleton();
     }
     return _instance;
 }

 public static class Extend extends Singleton {
     public Extend() {
         System.out.println("Extend ctor");
     }
     public void method() {}
 }
 private static Singleton _instance;

}
class Invoker {
 public static void main(String[] args) {
     System.out.println("main");
     Singleton.Extend e = new Singleton.Extend();
 }
}

Friday, February 1, 2013

FUCKING GAME OF METHOD OVERLOADING AND OVERRIDING


This ll demonstrate the concepts of static binding and dynamic binding , role of access modifiers in the overloading and overriding. Static Binding vs Dynamic binding Java Here are few important difference between static and dynamic binding in Java written in point format. knowledge of static and dynamic binding is require to understand Java code and find out any bugs and issue while running Java program. It also helps in troubleshooting and debugging in Java.
 1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.

 2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.

 3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.

4) Overloaded methods are bonded using static binding while overridden methods are bonded during run time. here is an example which will help you to understand both static and dynamic binding in Java.

5) Dynamic binding is slower than static binding because it occurs in runtime and spends some time to find out actual method to be called.

Here is project Structure




package com.source;
//Demo class that has all the overloaded and overriding methods 

package com.Java.one;

public class DemoClass {
  
    // overloaded constuctor
    public DemoClass(String one) {

     System.out.println("One argument constructor is called");
    }


    private DemoClass(String one, String two) {

     System.out.println("Two argument constructor is called");
    }

    protected DemoClass( int a,int b,int c) {

     System.out.println("Three argument constructor is called");
    
}

     DemoClass(int a,int b,int c,int d) {

      System.out.println("Four argument constructor is called");
    }

  //   constructor can't be static or final or static final
    /*public static  final DemoClass(float a){
     constructor can't be static or final or static final
    }
    */
    
    
     // ====================functions that has to be overridden
     public void overridePublicMethod(){

      System.out.println("Public method can be overridden");
     }
    
     private void overridePrivateMethod(){

      System.out.println("Private method can't be overridden");
     }
    

     protected void overrideProtectedMethod(){

      System.out.println("Proctected method can be overridden");
     }

    
      void overrideDefaultMethod(){

      System.out.println("default method can be overridden");
     }

    
     static void overrideStaticMethod(){

      System.out.println("Static  method can't be overridden");
     }
    

     public  final void overrideFinalMethod(){

      System.out.println("Final method can.t be overridden");
     }

}


=================END OF CLASS================================


// Class that extends the DemoClass

package com.Java.one;

public class ChildClassInSamePackage extends DemoClass{

    ChildClassInSamePackage(int a, int b, int c, int d) {
     super(a, b, c, d);
   // you have to call Base class constructor before you call child class one
    }

    protected ChildClassInSamePackage(int a, int b, int c) {
     super(a,b,c);
     System.out.println("Constructor of Child class is called");
     
    
    }

    public ChildClassInSamePackage(String one) {
     super(one);
    }


    // Lets see how and what methods of Base class can be overriden
    
    @Override
    public void overridePublicMethod() {
     super.overridePublicMethod();
     // this ll call the super class method
    }
    
@Override
void overrideDefaultMethod() {
    System.out.println("This is overriden method of Base class " +
      "and we are changing the Defination of " +
      "this mathod in the child class");
}
    



    @Override
    protected void overrideProtectedMethod() {
     System.out.println("This is protected overriden method of Base class " +
      "and we are changing the Defination of " +
     "this mathod in the child class");
    }
    
}

============================END OF CLASS=============================

// Class that demonstrate static Binding
package com.Java.one;

import java.util.Collection;
import java.util.HashSet;

public class StaticBinding {
   
 //overloaded method takes Collection argument
 public Collection sort(Collection c){

     System.out.println("Inside Collection sort method");
     return c;
 }
 
   
   //another overloaded method which takes HashSet argument which is sub class

 public Collection sort(HashSet hs){

     System.out.println("Inside HashSet sort method");
     return hs;
 }
    
 }

============================END OF CLASS=============================



// Class Demonstrate Dynamic Binding

package com.Java.one;

class Vehicle {

 public void start() {

     System.out.println("Inside start method of Vehicle");
 }
}

class Car extends Vehicle {

 @Override
 public void start() {
     System.out.println("Inside start method of Car");
 }
}


===============================END OF CLASS==========================

//  Class which is in other Class which extends DemoClass
package com.Java.two;
import com.Java.one.DemoClass;

public class ChildClassInOtherPackage extends DemoClass{
    public ChildClassInOtherPackage(String one) {
     super(one);  
    }
   
    @Override
    public void overrideProtectedMethod() {

     super.overrideProtectedMethod();
  System.out.println("Overriding...This method has to be public for making it " +
    "accessible from other package 
         although it's overriding a protected.");
    }
    

    @Override
    public void overridePublicMethod() {
     super.overridePublicMethod();
     //ok
    }
}

==========================END OF CLASS===============================

// MAIN CLASS

package com.Java.one;
import java.util.Collection;
import java.util.HashSet;

import com.Java.two.ChildClassInOtherPackage;

public class EntryPointClass {
    public static void main(String args[]){

System.out.println("==========DemoClass==============");

     DemoClass demoOneArg = new DemoClass("hi");
     // Methods that can be called using Base class
     
     demoOneArg.overrideDefaultMethod();
     demoOneArg.overrideFinalMethod();
     demoOneArg.overrideProtectedMethod();
     demoOneArg.overridePublicMethod();
     DemoClass.overrideStaticMethod();
     
     System.out.println("========ChildClassInSamePackage=======");

     ChildClassInSamePackage chClass = new ChildClassInSamePackage(1, 2, 3) ;
     chClass.overrideDefaultMethod();
     chClass.overrideFinalMethod();
     chClass.overrideProtectedMethod();
     chClass.overridePublicMethod();
     ChildClassInSamePackage.overrideStaticMethod();
     
  System.out.println("========ChildClassInOthPerackage=========");
     ChildClassInOtherPackage chOtherPak = new ChildClassInOtherPackage("Hello");
     
     chOtherPak.overrideFinalMethod();
     chOtherPak.overrideProtectedMethod(); // This method has to be public
     chOtherPak.overridePublicMethod();
//ChildClassInOtherPackage.overrideStaticMethdo(); //not allowed if in 
                                                   other package
     
     System.out.println("===StaticBinding===");
     
     /* we have overloaded sort() method, one of which accept Collection and
      * other accept HashSet. we have called sort() method with HashSet as
      * object but referenced with type Collection and when we run method with
      * collection as argument type gets called because it was bonded on compile
      * time based on type of variable (Static binding)  which was collection.
*/
         Collection c = new HashSet();
         StaticBinding et = new StaticBinding();
         et.sort(c);    
    System.out.println("================DynaimicBinding========================");  

         /*Car extends Vehicle and overrides its start() method and when we call start()
          * method from a reference variable of type Vehicle, it doesn't call start()
          * method from Vehicle class instead it calls start() method from Car
          * subclass because object referenced by Vehicle type is a Car object.*/
         
          Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
          vehicle.start();        //Car's start called because start() 
                                                is overridden method
  
           }
}

OUTPUT :

==================DemoClass==========================
One argument constructor is called
default method can be overridden
Final method can.t be overridden
Proctected method can be overridden
Public method can be overridden
Static  method can't be overridden

================ChildClassInSamePackage===============
Three argument constructor is called
Constructor of Child class is called
This is overriden method of Base class and we are changing 
the Defination of this mathod in the child class
Final method can.t be overridden

This is protected overriden method of Base class and 
we are changing the Defination of this mathod in the child class
Public method can be overridden

Static  method can't be overridden

================ChildClassInOtherPackage===================
One argument constructor is called
Final method can.t be overridden
Proctected method can be overridden

Overriding...This method has to be public for making it 
accessible from other package although it's overriding a protected.

Public method can be overridden

================StaticBinding==============================
Inside Collection sort method

================DynaimicBinding============================
Inside start method of Car


=========================END OF CONCEPT=====================

Playing with Access Modifiers in JAVA

To make you understand the concepts i have created the whole project.. The project structure is as below.










// Demo class which the super class
package com.source;

public class Demo {                                                            

 private int a;
 public int b;
 protected int c;
 int d;
 
 public Demo() {
 System.out.println("This is a public demo constructor");
 }
 
 private Demo( String one ){
 
  System.out.println("This is a private one argument demo constructor");
 }
 
 private void method(){
  System.out.println("This is a private method");
 }
 public  void method1(){
  System.out.println("This is a public method1");
 }
 protected  void method2(){
  System.out.println("This is a protected method2");
 }
 void method3(){
  System.out.println("This is a defualt method");
 }
 
 
 // Playing with inner classes
 
 public static class PublicStaticInnerClassOfDemo{
  
  public void InnerMethod(){
   System.out.println("public static class *Hi I am inside an 
              innerMethod which is public");
  }
  
  public static void staticInnerMethod(){
   System.out.println("public static class *Hi I am inside an 
       innerMethod which is public static  ");
  }
  
  private static void staticInnerMethodPrivate(){
   System.out.println("public static class *Hi I am inside an 
       innerMethod which is private  static ");
  }
  protected static void staticInnerMethodProtected(){
   System.out.println("public static class *Hi I am inside an 
          innerMethod which is protected  static ");
  }
  
   static void staticInnerMethodDefault(){
   System.out.println("public static class *Hi I am inside an 
        innerMethod which is default  static ");
  }
 }
 
 protected class ProtectedInnerClassOfDemo{
  
  public void InnerMethodPublic(){
   System.out.println("ProtectedInnerClassOfDemo *Hi I am inside an 
              innerMethod which is public");
  }
  
  private  void InnerMethodPrivate(){
   System.out.println("ProtectedInnerClassOfDemo *Hi I am inside an 
                 innerMethod which is private   ");
  }
  
  protected  void InnerMethodProtected(){
   System.out.println("ProtectedInnerClassOfDemo *Hi I am inside an 
           innerMethod which is protected   ");
  }
  
   void InnerMethodDefault(){
   System.out.println("ProtectedInnerClassOfDemo *Hi I am inside an
                   innerMethod which is default   ");
  }
 }
 
  class DefaultInnerClassOfDemo{
  public void InnerMethodPublic(){
   System.out.println("DefaultInnerClassOfDemo *Hi I am inside an 
               innerMethod which is public");
  }
  
  private  void InnerMethodPrivate(){
   System.out.println("DefaultInnerClassOfDemo *Hi I am inside an 
            innerMethod which is private   ");
  }
  
  protected  void InnerMethodProtected(){
   System.out.println("DefaultInnerClassOfDemo *Hi I am inside an 
              innerMethod which is protected   ");
  }
  
   void InnerMethodDefault(){
   System.out.println("DefaultInnerClassOfDemo *Hi I am inside an 
               innerMethod which is default   ");
  }
 }
 
 private class PrivateInnerClassOfDemo{
  // you can't extend private inner class of Demo
 }
 
   public  class PublicInnerClassOfDemo{
  
    /*The method innerMethod1 cannot be declared 
    static; static methods can only be declared in a 
    static or top level type*/
 //   public static void innerMethod1(){}
  
    public void InnerMethodPublic(){
   System.out.println("PublicInnerClassOfDemo *Hi I am inside an 
         innerMethod which is public");
  }
  
  private  void InnerMethodPrivate(){
   System.out.println("PublicInnerClassOfDemo *Hi I am inside an 
        innerMethod which is private   ");
  }
  
  protected  void InnerMethodProtected(){
   System.out.println("PublicInnerClassOfDemo *Hi I am inside an 
        innerMethod which is protected   ");
  }
  
   void InnerMethodDefault(){
   System.out.println("PublicInnerClassOfDemo *Hi I am inside an 
       innerMethod which is default   ");
  }
  
  
 }

}

=============================END OF DEMO CLASS ======================

// class which extends Demo class in the same package and will tell which
of the methods and variables can be accessed.

public class DemoInSamePackage extends Demo{

 
 public DemoInSamePackage() {
 System.out.println("DemoInSamePackage is called");
 }
 
 public  void mySamePackageMethod(){
  System.out.println("MySamePackage public method is accessing 
                     params of super class's variables");

  System.out.println("a === private but not allowed");
  System.out.println("b === public allowed "+b);
  System.out.println("c === pretected allowed"+c);
  System.out.println("d === default "+d);
  
  callingMethods();
 }

 private void callingMethods() {
 System.out.println("\n MySamePackage private method is 
                 accessing methods of super class");

 System.out.println("Not allowed to call the 
        private method of the super class");

 method1();
 method2();
 method3();
 
 }
}
=========================END OF THE CLASS=======================

// class that extends inner classes of Demo class 
       and tells which vars and methos can be accessible


public class ExtendInnerClassInSamePackage extends Demo.PublicStaticInnerClassOfDemo{

// When extending Demo.PublicStaticInnerClassOfDemo
 public void method(){

 Demo.PublicStaticInnerClassOfDemo.staticInnerMethod();    // ok 
 Demo.PublicStaticInnerClassOfDemo.staticInnerMethodDefault(); //ok
 Demo.PublicStaticInnerClassOfDemo.staticInnerMethodProtected(); //ok
  
 }
 
 /*When extending Demo.ProtectedInnerClassOfDemo*/
}



// Important 
/* 
 *  you can't extend the other classes but if you want you can do like below
  public class ExtendInnerClassInSamePackage extends Demo{
 class A extends ProtectedInnerClassOfDemo{ 
    public void  method(){
    Demo d = new Demo();
    Demo.PublicInnerClassOfDemo p = d.new PublicInnerClassOfDemo();
    p.InnerMethodPublic(); // ok
    p.InnerMethodProtected(); // ok 
    p.InnerMethodDefault(); // ok
     }
 }
 like this you can call all the classes but private class 
          and private methods of the classes you can't call 
 * 
 * */
=============================END OF CLASS===========================

// Main class that creates objects of classes

package com.source;

import com.sourcebits.DemoInOtherPackage;
import com.sourcebits.ExtendInnerClassInOtherPackage;

public class Main {
 
 public static void main( String [] args ){
  
   
 Demo d = new Demo();
  
 // you can't not call private constructor of 
             a class but default is ok
  // Demo privateConstructor = new Demo("hi");
  
 System.out.println("========Demo class accessing its own variables ");
 System.out.println("a === private not allowed "); 
//but if object is created inside the Demo class then it 
         can access private variable 
  
 System.out.println("b === public allowed "+d.b);
 System.out.println("c === protected allowed "+d.c);
 System.out.println("d === default allowed "+d.d);
  
 System.out.println("========Demo class accessing its own Methods ");
  
// d.method(); not allowed but if object is created inside the Demo 
          class then it can access private methods 

  d.method1(); // public method ok
  d.method2(); // protected ok 
  d.method3(); // defualt ok
  
  System.out.println("\n");
  System.out.println("When calls are from same package");
  DemoInSamePackage samePackageObj = new DemoInSamePackage();

samePackageObj.mySamePackageMethod(); // but if the method were private 
                                         could not have been accessed
  
 System.out.println("\n");
 System.out.println("When calls are from other package\n\n ");

 DemoInOtherPackage otherPackageObj =  new DemoInOtherPackage();
 otherPackageObj.myOtherPackageMethod();
  
      
System.out.println("When calls are from Inner classes which is in same package");

 ExtendInnerClassInSamePackage innersame = new ExtendInnerClassInSamePackage();
   innersame.method();
  innersame.InnerMethod(); // ok

  ExtendInnerClassInSamePackage.staticInnerMethod();  // ok
  ExtendInnerClassInSamePackage.staticInnerMethodDefault(); // ok
  ExtendInnerClassInSamePackage.staticInnerMethodProtected(); // ok

  
 System.out.println("When calls are from Inner classes which is in Other package");
       
 ExtendInnerClassInOtherPackage innerother = new ExtendInnerClassInOtherPackage();
   innerother.InnerMethod();
  innerother.method();

     ExtendInnerClassInOtherPackage.staticInnerMethod();  // ok
     ExtendInnerClassInOtherPackage.staticInnerMethodProtected(); //Ok
     
  
 }

}
===============================END OF CLASS==========================



/* class extends Demo   that tells if we can access vars and methods of Demo class*/

package com.sourcebits;

import com.source.Demo;

public class DemoInOtherPackage extends Demo{

 public DemoInOtherPackage() {
 System.out.println("DemoInOtherPackage default arguement constructor");
 }
 
 public void myOtherPackageMethod(){

  System.out.println("MyOtherPackage public method is 
                                    accessing variables of super class");
 
  System.out.println("a ===  private not allowed");
  System.out.println("b === public allowed "+b);
  System.out.println("c === protected allowed"+c);
  System.out.println("d === defalut not allowed");
  
  callingMethods();
 }
 private void callingMethods() {
  System.out.println("MyOtherPackage private method is 
                             accessing methods of super class");

System.out.println("Not allowed to call the private method of the super class");

  method1();
  method2();

System.out.println("Not allowed to call the default method of the super class");
  
  }
}
=============================END OF CLASS============================


// class that extends inner class of Demo class

package com.sourcebits;
import com.source.Demo;


public class ExtendInnerClassInOtherPackage extends Demo.PublicStaticInnerClassOfDemo{

// When extending Demo.PublicStaticInnerClassOfDemo
 public void method(){

Demo.PublicStaticInnerClassOfDemo.staticInnerMethod(); // ok
  
// ** Demo.PublicStaticInnerClassOfDemo.staticInnerMethodDefault();  // not allowed
  
Demo.PublicStaticInnerClassOfDemo.staticInnerMethodProtected(); //ok
  
 }
 
}





//Important 
/* 
 * you can't extend the other classes but if you want you can do like below

 public class ExtendInnerClassInOtherPackage extends Demo{

  class A extends PublicInnerClassOfDemo{ 

   public void  method(){

 Demo d = new Demo();
     Demo.PublicInnerClassOfDemo p = d.new PublicInnerClassOfDemo();

      
                   p.InnerMethodPublic(); // ok
                   InnerMethodProtected(); //  allowed 
     p.InnerMethodProtected(); // not allowed 
     p.InnerMethodDefault(); // not allowed 

     }
 }

NOTE : In the different package you can't extend  
         default,private class but public
 * 

when extending protected class :
public class ExtendInnerClassInOtherPackage extends Demo{

  class A extends ProtectedInnerClassOfDemo{ 

     public void  method(){

 //Demo d = new Demo();
       //Demo.ProtectedInnerClassOfDemo p = d.new Prote(); // can’t create object 

   InnerMethodPublic(); // ok
   InnerMethodProtected(); // ok
   InnerMethodDefault(); // not allowed 

     }
 }

 * */
 
=====================END OF THE CONCEPT=============================