欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

内部类入门

程序员文章站 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 ..");
	}

}