求助:关于私有内部类的实例化极其方法的调用?
请问各位高手私有的内部类如何在外部类的main方法中实例化?我的代码如下:
编译器报错的信息是:
OutClass.java:39: 无法从静态上下文中引用非静态 变量 this
InnerClass1 classDemo1 = new InnerClass1();
^
OutClass.java:44: 无法从静态上下文中引用非静态 变量 this
InnerClass2 classDemo2 = new InnerClass2();
后来我在两个内部类上加上了都加上了静态修饰符static结果编译运行都成功了,请各位高手为我解释一下是怎么回事?
public interface Destination
{
String readLabel();
}
public interface Contents
{
int value();
}
public class OutClass
{
private /*static*/ class InnerClass1 implements Destination, Contents
{
public String readLabel()
{
return "InnerClass1 String readLabel()";
}
public int value()
{
return 8;
}
}
private /*static*/ class InnerClass2 implements Destination, Contents
{
public String readLabel()
{
return "InnerClass2 String readLabel()";
}
public int value()
{
return 8;
}
}
/**
public Destination getInnerClass1()
{
Destination class1 = new InnerClass1();
return class1;
}
public Contents getInnerClass2()
{
Contents class2 = new InnerClass2();
return class2;
}
*/
public static void main(String[] args)
{
InnerClass1 classDemo1 = new InnerClass1();
System.out.println(classDemo1.readLabel());
System.out.print("InnerClass1 int value()");
System.out.println(classDemo1.value());
System.out.println();
InnerClass2 classDemo2 = new InnerClass2();
System.out.println(classDemo2.readLabel());
System.out.print("InnerClass2 int value");
System.out.println(classDemo2.value());
}
}
------解决方案--------------------package net.xiaohai;
/**
* @author haihai
*
*/
public class TestMain {
public TestMain() {
A a=new A();
}
public static void main(String[] args) {
new TestMain();
}
}
class A{
public A() {
B b=new B();
System.out.println(b.getInstance());
}
class B{
public B() {
}
private int getInstance(){
return 11111111;
}
}
}
不知道楼主的意思是不是,定义一个私有的非静态内部类,在外部调用其中的方法.私有的非静态内部类B在A的构造器实例,外部类如TestMain调用,打出11111.