黑马程序员技术交流社区
标题:
打印外部类和内部类的变量题目
[打印本页]
作者:
郭孟涛
时间:
2013-2-2 22:45
标题:
打印外部类和内部类的变量题目
// 题目: 创建一个包含实例内部类的类,外部类中定义一个名为str的String字符串并初始化任意值,在内部类中定义跟外部类同种类型且同名的变量,并在内部类中定义一个方法,分别打印外部类和内部类的变量。
public class HelloWorld
{
public static void main(String args[])
{
// 建立一个内部类对象,同时需一起建立外部类对象
Out.Inter ou = new Out().new Inter();
// 调用内部类的方法
ou.talk();
}
}
class Out // 创建一个外部类
{
String str = "out";// 定义一个外部类变量
class Inter // 创建一个内部类
{
String str = "inter"; // 创建一个内部类变量
void talk() // 定义一个内部类方法
{
System.out.println("外部类变量str="+Out.this.str); // 在this前加上外部类名,打印外部类变量
System.out.println("内部类变量str="+this.str); // 用this关键字打印内部类的变量
}
}
}
复制代码
作者:
彭彪
时间:
2013-6-14 11:00
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)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2