是否可以从一个static方法内部发出对非static方法的调用?

 *问题:是否可以从一个static方法内部发出对非static方法的调用?
 * 
 * 答:不可以。因为非static方法是要与对象关联在一起的,必须创建一个对象后,
 *         才可以在该对象上进行方法调用,而static方法调用时不需要创建对象,可以
 *    直接调用。也就是说,当一个static方法被调用时,可能还没有创建任何实例
 *    对象,如果从一个static方法中发出对非static方法的调用,那个非static
 *    方法是关联到哪个对象上的呢?这个逻辑无法成立,所以,一个static方法内部

 *    发出对非static方法的调用。

[java]  view plain  copy
  1. package java基础题目;  
  2.   
  3.   
  4. public class Test13 {  
  5.     // 静态成员  
  6.     public static String string = "static成员";  
  7.     // 普通成员  
  8.     public String string2 = "非static成员";  
  9.   
  10.     // 静态方法  
  11.     public static void method() {  
  12.         string = "sss";  
  13. //       string2 = "sss";  
  14.         // method2();//编译报错,因为静态方法里面只能调用静态方法或静态成员  
  15.         System.out.println("这是static方法,static方法与对象无关");  
  16.     }  
  17.   
  18.     // 普通方法  
  19.     public void method2() {  
  20.         string = "string1";  
  21.         string2 = "string2";  
  22.         method();// 非静态方法里面可以发出对static方法的调用  
  23.         System.out.println("这是非static方法,此方法必须和指定的对象关联起来才起作用");  
  24.     }  
  25.   
  26.     public static void main(String[] args) {  
  27.         Test13 test = new Test13();  
  28.         test.method2();// 引用调用普通方法  
  29.         test.method();// 引用调用静态方法  
  30.     }  
  31. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值