我们不能在java的外部类静态方法中创建内部类实例,但是它使用C#。请解释C#和Java的行为。非常感谢帮助。
C#代码:
class OuterClass
{
public static void Main(string[] args)
{
Nested nested = new Nested();
Nested.InnerNested innerNested = new Nested.InnerNested();
}
class Nested
{
public class InnerNested
{
}
}
}
Java代码:
public class OuterClass {
public static void main(String[] args) {
//Error: non-static variable this cannot be referenced from a static context
Nested out = new Nested();
//Error: non-static variable this cannot be referenced from a static context
Nested.InnerNested i = new Nested.InnerNested();
}
class Nested {
public class InnerNested { }
}
}
答案 0 :(得分:0)
Java static nested classes are similar to c# nested classes. Although one can access Inner nested classes in Java by using a reference of an object of the outer class:
Java Code:
public class OuterClass {
public static void main(String[] args) {
// Creates a reference of our outer class
NewClass myClass = new OuterClass();
// Uses it to create an instance of the nestled class
OuterClass.Nested nested = OuterClass.new Nested();
// Uses the nestled class object to instantiate an inner nestled object
OuterClass.Nested.InnerNested inner = nested.new InnerNested();
}
class Nested {
public class InnerNested { }
}
}
This answer was based on the following posts: