Re: [問題] 請教Main Class無法呼叫子類別
這篇看完應該可以解決所有疑問: http://c2.com/cgi/wiki?InnerClass
這邊點出幾個問題,
1. namespace:
你是在練習繼承,
但因為把 sub class 同時也寫成了 inner class,
導致觀念更難釐清。
簡單的說,inner class 的名稱應該是 SuperClass.SC,
SuperClass.SC SCDEMO = new SuperClass.SC();
所以改成上述後,你會遇到下一個問題:
an enclosing instance that contains SuperClass.SC is required
2. 上面那篇提到:
"An instance of an inner class can only live
attached to an instance of the outer class"
你需要 SuperClass 的 instance,才能 instantiate SC。
SuperClass.SC SCDEMO = new SuperClass().new SC();
現在程式可以動了,不過多產生了一個 SuperClass instance,
真的有這個必要嗎?
3. 也許你要的是 static inner class
static inner class 像是多了一層 namespace,
所以你不再需要 outer class 的 instance 了。
將 SC 加上 static 修飾後,你就可以寫:
SuperClass.SC SCDEMO = new SuperClass.SC();
話說回來,還在釐清繼承的觀念,
最好還是暫時先避開 inner class 的使用吧。
※ 引述《samxpjp (山姆)》之銘言:
: 各位大大我再練習 繼承的寫法但是遇到了一個問題 如下
: 請各位高手指點
: package inheritancedemo;
: //父類別
: public class SuperClass {
: public String Name;
: public int Age;
: //子類別
: class SC extends SuperClass{
: public int ID;
: }
: }
: ----------------------------------------------
: package InheritanceDemo;
: /**
: *
: * @author sam
: */
: public class SubClassDemo {
: /**
: * @param args the command line arguments
: */
: public static void main(String[] args) {
: SC SCDEMO=new SC(); <--一直說找不到SC,但改成父類別卻可以
: }
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.34.7.189
※ 編輯: tkcn 來自: 114.34.7.189 (07/07 20:17)
討論串 (同標題文章)