如下
Test2.Inn INN1 = test2.new酒店(4)你可以删除导入语句;
所以,整个代码可能是长相,
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
}
class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
让我告诉你另一种情况
让Test2的内部类的Test1类
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
,但代码韩元因为在Test1类的静态方法中无法访问Test2类,所以尚未编译。
所以,你可以做到这一点
静态类的Test2现在
,您可以通过声明Test2.Inn
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Test2.Inn inn = test2.new Inn(3);
Test2.Inn inn1 = test2.new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
static class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
访问静态成员的Test2类测试1和它的内部类的酒店
然后,上面的代码有点难看,所以我终于可以自己编写代码
import Test1.Test2.Inn;
public class Test1 {
public static void main(String[] args) {
int sum = 1;
Test2 test2 = new Test2(2);
Inn inn = new Inn(3);
Inn inn1 = new Inn(4);
for (int i = 0; i < 9; i++){
sum = (sum + 1) * 2;
}
System.out.println(sum);
}
static class Test2 {
private int test;
public Test2(int test) {
this.test = test;
}
static class Inn{
private int inn;
public Inn(int inn) {
this.inn = inn;
}
}
}
}
我认为这是关于课程的范围或可达性。
内部类的成员仅在内部类的范围内是已知的,并且外部类可能不会使用它。如果任何类Test2以外的代码尝试实例化类Inn,则Java编译器会生成一条错误消息。一般来说,嵌套类与任何其他程序元素没有区别:它只在其封闭范围内是已知的。请提及您想要添加最终方法的课程。 – Tehmina
使用Test2.Inn inn1 = test2.new Inn(4); – tommybee