java子类继承父类问题
java课作业题
父类 Author只有有参构造方法
class Author{
String name;
String email;
char gender;
public Author(String name,String email,char gender){
this.name=name;
this.email=email;
this.gender=gender;
}
}
子类 book只有有参构造方法
class Book extends Author{
String name;
Author author;
double price;
public Book(String name,Author author,double price){
super(name,email,gender);
this.name=name;
this.author=author;
this.price=price;
}
在主函数中
Author cA=new Author(name,email,gender);
Book zB=new Book(name,cA,price);
super()一定要写和cA里的参数一样吗,cA的参数变了,那不是还要改super()里的参数吗
java继承中对构造函数是不继承的。
以下是例子:
public class FatherClass {
public FatherClass() {
System.out.println(100);
}
public FatherClass(int age) {
System.out.println(age);
}
}
public class SonClass extends FatherClass{
public SonClass() {
}
public SonClass(int c) {
System.out.println(1234);
}
public static void main(String[] args) {
FatherClass f = new FatherClass(28);
SonClass s = new SonClass(66);
}
}
编译后执行结果如下是什么呢?
分析:1. FatherClass f = new FatherClass(28);这句没有必要解释
2.SonClass s = new SonClass(66);执行这句时,调用
public SonClass(int c) {
System.out.println(1234);
}
在这个构造函数中,等价于
public SonClass(int c) {
super();//必须是第1行,否则不能编译
System.out.println(1234);
}
所以结果是 100
1234
3.如果子类构造函数是这样写的
public SonClass(int c) {
super(22);//必须是第1行,否则不能编译
ca的参数变了,为何要改super()的参数?
cA已经和zB绑定到一起了