内部类入门
程序员文章站
2022-05-23 21:05:30
...
内部类:在类内部又定义类,内部类作为外部类的一个field
/* * BeginInnerClass.java * * Introduce Inner class * 1. How to get Inner class in out class * 2. How to get Out class instance in Inner Class * 3. outter. new Inner() and Outter.this */ package com.thinking.innerclass; public class BeginInnerClass { // you can use other modifier public/protected/private private class Inner { private String name; public Inner(String name) { name = this.name; } // public void say(String str) { System.out.println("innser class:" + str); } //generate outter class reference public BeginInnerClass getOutterClass() { return BeginInnerClass.this; } } // the name of method same as inner class method public void say(String str) { System.out.println("outter class: " + str); } public Inner returnInnerClass() { System.out.println(" method will return innerclass .."); return new Inner("zhaoyunpeng InnerClass"); } public static void main(String[] args) { BeginInnerClass outter = new BeginInnerClass(); //Reference Inner class BeginInnerClass.Inner inner = outter.returnInnerClass(); inner.say("zhaoyunpeng called.."); // BeginInnerClass.Inner inner2 = new BeginInnerClass.Inner("hello, world"); BeginInnerClass outter2 = new BeginInnerClass(); //Create inner class through outterClassInstance.new BeginInnerClass.Inner inner2 = outter2.new Inner("hello, world"); inner2.say(" hello called .."); //inner class get outter class reference through OutterClassName.this inner2.getOutterClass().say("zhaoyunpneg2 called .."); } }
上一篇: 策略模式的一个简单例子
下一篇: php的错误和异常处理