您的位置:首页 > 其它

【转载】关于“静态方法不能调用非静态方法”的补充解释

2009-05-08 05:27 351 查看
找到一篇文章验证了我之前的想法(static方法调用non-static方法必须通过传对象参数的方式,因为non-static方法是与对象实例对应的)

http://hi.baidu.com/danghj/blog/item/1f96d1eac9771cd6d539c986.html

静态方法中调用非静态方法

我们都知道,静态static方法中不能调用非静态non-static方法,准确地说是不能直接调用non-static方法。但是可以通过将一个对象的引用传入static方法中,再去调用该对象的non-static方法。

其实这个事实的应用很经常,以至于我们不去重视:在主函数(static方法)中我们经常创建某个类的实例,再利用其饮用变量调用它的非静态方法。

//StaticMethodTest.java

//A ststic method cannot call a non-static method, but we can transfer a object reference, which include a non-static metho to the static method, thus, wo can call that non-static method in a indirect way.

public class StaticMethodTest{

void NonStaticMethod(){

System.out.println("This is a non-sataic method.");
}

static void StaticMethod(StaticMethodTest s){

System.out.println("This is a static method.");

s.NonStaticMethod();

}

public static void main(String[] args) {
StaticMethodTest sObj=new StaticMethodTest();

StaticMethod(sObj); //在主函数中可以直接调用静态方法

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐