父类:
package com.infodeliver.test.core;public class ProjectClass {
/**
* ProjectClass
*/
public ProjectClass() {
System.out.println("In ProjectClass's Constructor!!");
} public void process(){
System.out.println("in ProjectClass.process()");
}
}子类:
package com.infodeliver.test.core;public class ApatherProject extends ProjectClass{
ApatheeProject adaptee = null;
/**
* ApatherProject
*/
public ApatherProject() {
//super();
} /**
* process
*/
public void process() {
//super.process();
if(adaptee==null)
adaptee = new ApatheeProject();
adaptee.Process();
}public static void main(String[] args){
ApatherProject a= new ApatherProject();
// a.process();
}
}
执行的结果:
In ProjectClass's Constructor!!
问题:
1.为什么我在子类的构造函数中,不用super关键字也照样会调用父类中的构造函数?这里的super不是显得可有可无了吗?
2.看到别人在他的类实现了一个接口implements Interface1{},并且在这个类里的构造函数里用了super关键字又能起到什么样的作用呢?能调用接口中的什么东西吗??谢谢!!
package com.infodeliver.test.core;public class ProjectClass {
/**
* ProjectClass
*/
public ProjectClass() {
System.out.println("In ProjectClass's Constructor!!");
} public void process(){
System.out.println("in ProjectClass.process()");
}
}子类:
package com.infodeliver.test.core;public class ApatherProject extends ProjectClass{
ApatheeProject adaptee = null;
/**
* ApatherProject
*/
public ApatherProject() {
//super();
} /**
* process
*/
public void process() {
//super.process();
if(adaptee==null)
adaptee = new ApatheeProject();
adaptee.Process();
}public static void main(String[] args){
ApatherProject a= new ApatherProject();
// a.process();
}
}
执行的结果:
In ProjectClass's Constructor!!
问题:
1.为什么我在子类的构造函数中,不用super关键字也照样会调用父类中的构造函数?这里的super不是显得可有可无了吗?
2.看到别人在他的类实现了一个接口implements Interface1{},并且在这个类里的构造函数里用了super关键字又能起到什么样的作用呢?能调用接口中的什么东西吗??谢谢!!
原因么很自然,因为你需要分配合适的内存空间给新创建的实例,子类自己当然不知道
父类创建时需要的空间是什么样的,就让父类的构造器先来完成这个工作了。如果你不用super指明,就会调用默认的构造器咯(空参数)。至于实现接口的那个问题,你说的我不太明白。
但super 一定是用在 Class Hierarchy中的,和接口应该没有太多关系。
楼主的意思是用了super()关键字在这里没有啥效果!!我也不明白,学习中!!!怎么样才能在这里能看出super的效果呢??
父类 :昆虫,有成员变量为 翅膀,触角,腿,构造昆虫的构造函数对这三个成员变量付值
子类 :蟋蟀,除了上面3种特征外,增加一项颜色。定义蟋蟀的构造函数时,把它属于昆虫的共性的东西直接调用父类的构造函数。即super(翅膀,触角,腿);颜色则另外辅值
Parent() {} //////第2行
Parent(int i) { }
}class Child extends Parent {
Child() {
super(1); ///////第8行
}
}///:~第2行和第8行可以注释掉任何一行,但不能同时注释掉。否则将不能编译。2. super永远指的是类,和接口无关。