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

  1. class TD
  2. {
  3. int y=6;
  4. static class Inner
  5. {
  6. static int y=3;
  7. void show()
  8. {
  9. System.out.println(y);
  10. }
  11. }
  12. }
  13. class TC
  14. {
  15. public static void main (String[] args)
  16. {
  17. TD.Inner ti=new TD().new Inner();
  18. ti.show();
  19. }
  20. }
复制代码

视频里说static int y=3; 在非静态内部类里不能定义成静态的。我把内部类定义成静态了怎么又出错。

7 个回复

倒序浏览
  1. class TD {
  2.         int y = 6;

  3.         static class Inner {
  4.                 static int y = 3;

  5.                 void show() {
  6.                         System.out.println(y);
  7.                 }
  8.         }
  9. }

  10. class TC {
  11.         public static void main(String[] args) {
  12.                 TD.Inner ti = new TD.Inner();
  13.                 ti.show();
  14.         }
  15. }
复制代码
回复 使用道具 举报
李成 发表于 2012-4-5 10:50

这是为什么呢??
回复 使用道具 举报
李成 发表于 2012-4-5 10:50

呃。。了解了 。迷过来了。谢谢啊
回复 使用道具 举报
class TD
{
int y=6;
static class Inner
{
static int y=3;
         void show()
{
System.out.println(y);
}
}
}
class TC
{
public static void main (String[] args)
{
//new TD.Inner().show();


TD.Inner ti=new TD. Inner();
        ti.show();


}
}

在外部其他类中,如何直接访问static内部类的非静态成员呢?
        new Out.Inner().function();

        在外部其他类中,如何直接访问static内部类的静态成员呢?
        user.Inner.function();

        注意:当内部类中定义了静态成员,该内部类必须是static的。
                当外部类中的静态方法访问内部类时,内部类也必须是static.红色的字体有两种写法,你看看哪种适合你。   外加点说明就看那得更加清楚了:
回复 使用道具 举报
静态就不用再创建实例了,直接可调用了,所以如楼上直接就用new TD.Inner();而不用 new TD().new Inner();
回复 使用道具 举报
17行 TD.Inner ti=new TD().new Inner();
因改
TD.Inner ti=new TD.Inner();
回复 使用道具 举报
class TD
{
        int y = 6;

        static class Inner
        {
                static int y = 3;
                static void show()
                {
                        System.out.println(y);
                }
        }
}
/*
当内部类被static修饰后,其他外部要访问静态内部类的静态成员,其实就是直接通过类名调用:TD.Inner.show();

*/
class TD1
{
        int y = 6;

        static class Inner
        {
                static int y = 3;
                void show()
                {
                        System.out.println(y);
                }
        }
}
class P1
{
        public static void main(String[] args)
        {
               
                TD.Inner.show();
                new TD1.Inner().show();
        }
}
result:
3
3
/*
当内部类被static修饰后,其他外部要访问静态内部类的非静态成员,是通过内部类的对象访问的:
new TD1.Inner().show();
*/
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马