Tuesday, 19 April 2011

What are non static inner classes?

The different type of static inner classes are: Non - static inner classes – classes associated with the object of the enclosing class. Member class - Classes declared outside a function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.

public class InnerClass {
class MemberClass {
public void method1() { }
}
}
Method local class – The inner class declared inside the method is called method local inner class. Method local inner class can only be declared as final or abstract. Method local class can only access global variables or method local variables if declared as final
public class InnerClass {
int i = 9;
public void method1() {
final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}

Anonymous inner class - These are local classes which are automatically declared and instantiated in the middle of an expression.  Also, like local classes, anonymous classes cannot be public, private, protected, or static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a constructor. They can implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static

Some examples:
public class MyFrame extends JFrame {
JButton btn = new JButton();
MyFrame() {
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}

Anonymous class used with comparator
List<Parent> l = new ArrayList<Parent>();
l.add(new Parent(2));
l.add(new Parent(3));
Collections.sort(l, new Comparator() {
public int compare(Object o1, Object o2) {
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;

if (prt1.getAge() > prt2.getAge()) {
return -1;
}else if(prt1.getAge()<prt2.getAge()) {

return 1;
} else {

return 0;
}
}
});

No comments:

Post a Comment