方法的选择

本文解析了Java语言规范中关于方法调用位置的限制及实例变量访问的特殊规则,通过具体代码示例说明了void方法不能作为表达式的一部分,以及super关键字在变量访问与方法调用中的不同行为。

 

 

 

解读JLS:https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.3

If the compile-time declaration is void, then the method invocation must be a top level expression (that is, the Expression in an expression statement (§14.8) or in the ForInit or ForUpdate part of a for statement (§14.14)), or a compile-time error occurs.

 

class T1 {
	public void a(){}
	public void b(){}
	public void test(int i){
		for(a();i<0;i++,b()){
			
		}
	}
}

 

 

解读JLS:https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.4.2

When accessing an instance variable, super means the same as a cast of this (§15.11.2), but this equivalence does not hold true for method invocation. This is demonstrated by the example:

class T1 {
	int a = 1;
}

class T2 extends T1 {
	int a = 2;
}

class T3 extends T2 {
	public void test() {
		System.out.println(((T1) this).a);
		System.out.println(((T2) this).a);
	}
}

public class TestB {
	public static void main(String[] args) {
		T3 t3 = new T3();
		t3.test();
	}
}

打印的结果为1、2  

转载于:https://www.cnblogs.com/extjs4/p/9249414.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值