JAVA菜鸟入门(13) outer class与inner class的之间能互相使用field或者method吗?

Nested classes are divided into two categories: static and non-static. 

1. Nested classes that are declared static are called static nested classes. 

2. Non-static nested classes are called inner classes.


outer class与inner class的之间能互相使用field或者method吗?

可以。


代码如下:

package FFtest2;

public class FFOuter {
	private String first;
	private int second;
	public FFOuter(String l, int r) {
		first = l;
		second = r;
	}
	
	public String addStringInteger(String first, int second) {
		return first + Integer.toString(second);
	}
	
	/**
	 * test1 
	 * Outter class has access to inner private field
	 * Outter class has access to inner method
	 */
	public void outterPrint() {
		FFOuter.InnerDisplay temp = this.new InnerDisplay("frog", 20);
		System.out.println("Outer class uses Inner class field : " + temp.innerFirst + ", " + temp.innerSecond);
		temp.print(first, second);
	}
	
	private class InnerDisplay {
		private String innerFirst;
		private int innerSecond;
		public InnerDisplay() {
			this("Somebody", 0);
		}
		public InnerDisplay(String s, int i) {
			innerFirst = s;
			innerSecond = i;
		}
		public void print (String f, int s) {
			System.out.println("Inner class: first = " + f+  ", second = " + s);
		}
		
		/**
		 * test 2 
		 * Inner class has access to outer class private field
		 */
		public void print () {
			System.out.println("Inner class uses outer class: first = " + first+  ", second = " + second);
		}
		
		/**
		 * test 3 
		 * Inner class has access to outer class method.
		 */
		public String add(String first, int second)
		{
			return addStringInteger(first, second);
		}
	}
	
	public static void main (String [] args){
		
		/** 
		 * test 4
		 * in main(), call outter method 
		 * */
		FFOuter outter = new FFOuter("zebra", 25);
		outter.outterPrint();
		
		/**
		 * test 5
		 * in main(), call inner method 
		 */
		InnerDisplay innerDisplay = outter.new InnerDisplay();
		innerDisplay.print();
		System.out.println(innerDisplay.add("iphone", 10));
	}
}



输出结果

Outer class uses Inner class field : frog, 20

Inner class: first = zebra, second = 25

Inner class uses outer class: first = zebra, second = 25

iphone10



你可能感兴趣的:(FundamentalJava)