靜態內部類中可以定義靜態方法嗎?如果可以,怎樣訪問外部類中的非靜態變量和靜態變量及它所在的靜態內部類中的不同變量?靜態內部類中可以定義靜態變量嗎?如果可以外部類如何訪問它呢?
??public class HelloWorld {????
???? // 外部類中的靜態變量score
???? private static int score = 84;?????
???? // 創建靜態內部類
???? public? static? class SInner {
???????? // 內部類中的變量score
???????? int score = 91;??????
???????? public static void show() {
???????????? System.out.println("訪問外部類中的score:" + HelloWorld.score? );
???????????? System.out.println("訪問內部類中的score:" + score);
???????? }
???? }
???? // 測試靜態內部類
???? public static void main(String[] args) {
???????? // 直接創建內部類的對象
???????? SInner si=new SInner();
???????? // 調用show方法
???????? si.show();
???? }
2015-10-04
。。eclipse里面沒有報錯??!
package com.shiyan;
public class Outer2 {
? ?static int score1=150; ? ? ? ? ? //外部類的靜態變量
? ?int score2=61; ? ? ? ? ? ? ? ? ? //外部類的普通變量
? ?
? ?public static class Inner{ ? ? ? //靜態內部類Inner
? static int score1=89; ? ? ? ? ?//靜態內部類的靜態變量
? int score2=88; ? ? ? ? ? ? ? //靜態內部類的普通變量
??
? public static void show(){ ? ? ? ?//靜態內部類中的靜態方法
? System.out.println(Outer.score1);
? System.out.println(new Outer().score2);//為什么不能用Outer.this.score2
? System.out.println(score1);
? System.out.println(new Inner().score2);//為什么不能直接用score2;
? }
? ?}
? ?//內部測試類
? ?public static void main(String[] args) {
System.out.println(score1);
System.out.println(new Outer().score2);
// Inner.show();
/*Inner in=new Inner();
in.show();*/
new Inner().show();
}
??
}
輸出:
150
62
99
62
89
88
2015-07-10
不能定義靜態方法