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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郭孟涛 高级黑马   /  2013-2-2 22:45  /  1446 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. // 题目: 创建一个包含实例内部类的类,外部类中定义一个名为str的String字符串并初始化任意值,在内部类中定义跟外部类同种类型且同名的变量,并在内部类中定义一个方法,分别打印外部类和内部类的变量。

  2. public class HelloWorld
  3. {
  4.     public static void main(String args[])
  5.     {
  6.         // 建立一个内部类对象,同时需一起建立外部类对象
  7.         Out.Inter ou = new Out().new Inter();
  8.         // 调用内部类的方法
  9.         ou.talk();
  10.         
  11.         
  12.     }
  13. }
  14. class Out // 创建一个外部类
  15. {
  16.     String str = "out";// 定义一个外部类变量
  17.     class Inter // 创建一个内部类
  18.     {
  19.         String str = "inter"; // 创建一个内部类变量
  20.         void talk() // 定义一个内部类方法
  21.         {
  22.             System.out.println("外部类变量str="+Out.this.str); // 在this前加上外部类名,打印外部类变量
  23.             System.out.println("内部类变量str="+this.str); // 用this关键字打印内部类的变量
  24.         }
  25.     }
  26.    
  27. }
复制代码

1 个回复

正序浏览
Out.Inter ou = new Out().new Inter();    这个地方好像有问题的????

No enclosing instance of type Test7 is accessible. Must qualify the allocation with an enclosing instance of type Test7 (e.g. x.new A() where x is an instance of Test7).

        at com.itheima.Test7.main(Test7.java:10)
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马