Post on 15-Jan-2015
description
transcript
Inner Class
Group 3 Kompongsom Class
Introduction
Member : Leang BunrongChea SocheatHeak MenghokHoun SreynavBouy Sodeth
Content
• Static inner class• Local inner class• Anonymous inner class
Inner Class
Overview of Nested Class (Inner Class)
Nested Class
Non-Static Nested Class (Inner Class)
Static Nested Class
Local inner Class
Anonymous inner Class
Why Inner Class?
• A big class to small class• Easy to maintenance• Increased encapsulation
Static Inner Class
• Can use Public, Protected, Default, Private modifier• marked with static modifier. • doesn’t share any special kind of relationship with
an instance of outer class. • It can access static data members of outer class
including private.• Static inner class cannot access non-static (instance)
data member or method of its Outer class.
Static Inner Class (cont.)Example:
public class Outer {static int code=1;static String name="Cheat";static int birth=1994;static class Inner {public String toString(){return code+"\t"+name+"\t"+birth;}}public static void main(String[] args) {Outer.Inner n = new Outer.Inner();System.out.println(n.toString());}
}
Local Inner Class
• Local class can access local variable that are declare final keyword
• We can create Local class in the method• We can not declare some static member
Local Inner Class (cont.)Ex:
class Simple{ private int data=30; //instance variable void display(){class Local{void msg(){System.out.println(data);}}Local l=new Local();l.msg();}public static void main(String args[]){Simple obj=new Simple();obj.display();}
}
Anonymous Inner Class
• No-name declaration• Declared and instantiated at the same time• Must implement an Interface or extend a Class• No ‘implements’ or ‘extends’ keywords used• No Constructor• Can not define static fields, static method or
static class except constants (static final).
Anonymous Inner Class (cont.)Example:
Class MyClass{JButton button = new JButton("Click Me");button.addActionListener(new ActionListener() {
@Overridepublic void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Message", "Title", JOptionPane.ERROR_MESSAGE);
}});
}
Thank for your pay attention