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