A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 山水游客 中级黑马   /  2012-5-24 15:02  /  1158 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Outer
{
   
   static int  x  = 3;
   
   class Inner
   
   {
      
      int   x  = 4;
      
      //static void function() //error ?
      void function()
      {
      
         int x = 5;
         // System.out.println("inner :" +Outer.this.x);
         System.out.println("inner :" + x);
      }
   }
   
   //static void method() //true
    void method()
   {
   
      System.out.println(x);
   }
}
public class innerClassDemo
{
   
   public static void main(String[] args)
   {
   
      //Outer.method();  //在方法名前添加static直接调用
       Outer out= new Outer();
       out.method();
      
      Outer.Inner inner = new Outer().new Inner();
      inner.function();
   }
   
}问题
1.  在main方法中调用类中的方法,一般都会先实例化一个对象,再调用方法实现相应的功能,为什么不能在方法前面加上static 直接通过类名.方法名去实现功能呢?这样岂不是更好。
2.       同样的思路,为什么外部类的方法可以在前面添加static 而内部类方法前不能添加呢?

2 个回复

倒序浏览
     1. 如果所有的方法都加上了static 修饰方法名字的话,就是相当于,你们家的东西都是公有的,谁想用就可以用了,你不纠结吗?
   
     创建对象调用,就是只有你 可以用自己家的东西。

   2. 要是在内部类里面加static  方法 ,你必须也要把   类 static 就可以再内部类里写  static方法了。
回复 使用道具 举报
本帖最后由 小小企鹅 于 2012-10-27 22:42 编辑

1.静态方法在程序启动时放在内存中,这样也可以调用方法
2.static方法只能在:static修饰的类内部类声明,或者在顶层类声明
class Outer{
        static class Inner{
                static void fun(){
                        
                }
        }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马