Wednesday, March 4, 2015

Static Inner Class

Static Inner class does can not access outer class's instance variable and non-static method of outer class. It is a way of logically grouping classes that are only used in one place. Nesting such "helper classes" makes their package more streamlined. Static Inner class is actually not an inner class, it behaves like top level class.

public class OuterClass {


void displayOuterClass()
{
System.out.println("From outer class");
}

public static class InnerClass
{
void displayFromInnerClass()
{
System.out.println("From inner class");
}
}

        
}


public class MyClass
{
  public static void main(String[] args)
{
OuterClass outer=new OuterClass();
outer.displayOuterClass();
OuterClass.InnerClass inner=new OuterClass.InnerClass();
inner.displayFromInnerClass();

}
}




Tuesday, March 3, 2015

Anonymous Classes

There are 2 different kinds of anonymous classes.
1. Plain Old Anonymous Inner Classes
2. Argument declared anonymous Inner Classes.

Plain Old Anonymous Inner Classes version has 2 more flavours.


1.a. Plain Old Anonymous Inner Classes  (Flavor One): Subclass type

    public class Animal {
void eat()
{
System.out.println("Animal eats");
}
}

public class Forest {

public static void main(String[] args)
{
Animal animal=new Animal(){
void eat()
{
System.out.println("Dog eats");
}
};

animal.eat();
}
}


Here animal is instance of anonymous class which has been extended from Animal class. Note that, only overriden method can be accessed from animal object as per polymorphism laws.

1.b. Plain Old Anonymous Inner Classes (Flavor Two): Interface type

public interface Eatable {

void eat();
}

public class Forest {

public static void main(String[] args)
{
Eatable eAnimal=new Eatable()
{
public void eat()
{
System.out.println("Animal can eat");
}
};
eAnimal.eat();
}
}

This type of anonymous inner class implements only one Interface.

2. Argument declared anonymous inner class

Suppose we have an interface

public interface Eatable {

void eat();
}

and a function that takes an object which type has implemented that interface.

void letsEat(Eatable man)
{
man.eat();
}

In that case, we can create a class and implementes that interface and then we can pass it to the function. The smart way is to use argument declared anonymous inner class.

public class Forest {

void letsEat(Eatable man)
{
man.eat();
}
public static void main(String[] args)
{
Forest forest=new Forest();
forest.letsEat(new Eatable(){
public void eat()
{
System.out.println("I wanna eat");
}
});
}
}