60 likes | 191 Views
Inner class. Static inner class. 範例 程式 1: public class InnerClass1 { static int i; final int j = 1; int k; public static void main(String[] args ) { Nested n = new Nested(); n.amethod (); } static class Nested { public void amethod () {
E N D
Static inner class 範例程式1: public class InnerClass1 { static int i; final int j = 1; int k; public static void main(String[] args) { Nested n = new Nested(); n.amethod(); } static class Nested { public void amethod() { System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("k = " + k); } } } • Static inner class: • 只能存取外部類別的static field • Inner class 有static 關鍵字 可以如何修改?? • "InnerClass1.java": Error #: 308 : non-static variable j cannot be referenced from a static context • "InnerClass1.java": Error #: 308 : non-static variable k cannot be referenced from a static context
MEMBER INNER CLASSES 範例程式2: public class InnerClass2 { static int i = 10; final int j = 1; int k; public static void main(String[] args) { Nested c = new InnerClass2().new Nested(); c.amethod(); } class Nested { public void amethod() { System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("k = " + k); } } } • Member inner classes: • 能存取外部類別的所有field • Inner class 沒有static 關鍵字 執行結果: i = 10 j = 1 k = 0
LOCAL INNER CLASSES public class InnerClass3 { public static void main(String[] args) { InnerClass3 in = new InnerClass3(); in.amethod(); } public void amethod() { final staticint i = 100; finalint j = 10; class NestedC { public void bmethod() { System.out.println("i = " + i); System.out.println("j = " + j); } } new NestedC().bmethod(); } } • Local inner classes • 宣告在method中的類別,故Local inner classes 不能有static,也不能有modifier(public、protected 、private) • 可以存取外部類別的所有變數,但是不能存取method的local變數 "InnerClass3.java": Error #: 480 : local variable j is accessed from within inner class; needs to be declared final
ANONYMOUS INNER CLASSES • 沒有名稱的類別,匿名類別最常用在event的處理上
import java.awt.*; import java.awt.event.*; public class InnerClass4 extends Frame { public InnerClass4() { Button b = new Button("Click me!"); b.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Click me!"); } } ); this.add(b); this.setSize(200, 100); this.show(); } public static void main(String[] args) { InnerClass4 in = new InnerClass4(); } } • anonymous inner class : • overriding methods • 存取外部類別的所有變數