關于靜態(tài)內部類直接訪問外部類的非靜態(tài)成員 new 外部類().成員 能不能賦值
//外部類
public class HelloWorld{
? private int num = 1;
? // 外部類中的靜態(tài)變量score
? private static int score = 84;
??
? // 創(chuàng)建靜態(tài)內部類
public? ? ?static? ? ?class SInner {
? ? ? // 內部類中的變量score
? ? ? int score = 91;
? ? ??
public void show() {
System.out.println("訪問外部類中的score:" +? ? ?HelloWorld.score? ? ? );
System.out.println("訪問內部類中的score:" + score);
HelloWorld hello = new HelloWorld();
System.out.println(hello.num);//這句對的
public int a = hello.num;//這句錯了
}
}
// 測試靜態(tài)內部類
public static void main(String[] args) {
// 直接創(chuàng)建內部類的對象
? ? ? SInner si = new SInner();
? ? ??
? ? ? // 調用show方法
si.show();
System.out.println(si.a);//這句錯了
}
}
上面的這三句
public int a = hello.num;
System.out.println(si.a);
這兩句是錯的
System.out.println(hello.num);
這句是對的
2020-06-25
不好意思,看著這個代碼上的get方法,覺得作用會不會不大?
2020-01-10
已解決
我把東西寫在函數里了。。。
下面是對的
package com.test.second;
//外部類
public class test2 {
? private int num = 1;
? // 外部類中的靜態(tài)變量score
? private static int score = 84;
??
? // 創(chuàng)建靜態(tài)內部類
public? ? ?static? ? ?class SInner {
? ? ? // 內部類中的變量score
? ? ? int score = 91;
? ? ??
public void show() {
System.out.println("訪問外部類中的score:" +? ? ?test2.score? ? ? );
System.out.println("訪問內部類中的score:" + score);
}
public int getNum() {
return a;
}
// test2 hello = new test2();
// private int a = hello.num;
int a = new test2().num;
}
// 測試靜態(tài)內部類
public static void main(String[] args) {
// 直接創(chuàng)建內部類的對象
? ? ? SInner si = new SInner();
? ? ??
? ? ? // 調用show方法
si.show();
System.out.println(si.a);
}
}