public class invokeMethod{
public void showMsg(){
System.out.println("this is showMsg");
}
public void callOther(){
showMsg();
}
public static void main(String args[]){
invokeMethod ob=new invokeMethod();
ob.callOther();
}
}
在上例中,方法callOther()和方法showMsg()处在同一个类中,所以调用后者时直接使用方法名就可以了。
令人比较疑惑的地方是在main()方法中,此处调用callOther()方法使用了看似比较麻烦的办法,先创建一个对象ob,再用对象名.方法的格式来调用方法,这似乎是多此一举
这么解释可能有的同学还有疑惑,为什么callOther方法又能够直接调用showMsg(),难道它能保证在调用后者时对象已经存在,答案却是如此,因为callOther本身是实例方法,它在执行时一定有对象存在,基于这个前提,它才能够直接调用showMsg方法。
编辑特别推荐: