内部类入门
程序员文章站
2022-05-23 19:10:01
...
内部类:在类内部又定义类,内部类作为外部类的一个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 .."); } }
上一篇: 页面之间的关联性,是否会影响搜索引擎抓取
下一篇: c语言:判断两个数组是否有相同的元素