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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值