作者tkcn (sayuan)
看板java
标题Re: [问题] 请教Main Class无法呼叫子类别
时间Sun Jul 7 17:07:18 2013
这篇看完应该可以解决所有疑问:
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)