/*按要求完成如下类的设计:
a. 假设“三角形”类派生出子类“等腰三角形”,等腰三角形派生出子类“等边三角形”;
b. 三角形类有属性三条边,并在构造函数中为三边赋初值;
c. 等腰三角形中无新增属性,提供2个参数的构造函数,在构造函数中为三边赋初值;
d. 等边三角形中无新增属性,提供1个参数的构造函数,在构造函数中为三边赋初值。
e. 在main中创建普通三角、等腰三角、等边三角各1个,并输出三角形的信息。
*/
class Triangle{
private int a,b,c;
public Triangle(int x,int y,int z){
a=x; b=y; c=z;
}
public String toString() {
return "("+a+","+b+","+c+")";
}
}
class DengYao extends Triangle{
public DengYao(int x,int y){
super(x,x,y); //父类是Triangle(int x,int y,int z),三个参数
}
}
class DengBian extends DengYao{
public DengBian(int x) {
super(x,x); //父类是DengYao(int x,int y),两个参数
}
}
class APP{
public static void main(String [] args) {
Triangle i = new Triangle(3,4,5); //看本类的构造函数有几个参数
DengYao j = new DengYao(6,7);
DengBian k = new DengBian(9);
System.out.print(i+"\n"+j+"\n"+k);
}
}
若子类不调用super,使用在父类新增无参构造函数的方法:
class Triangle{
private int a,b,c;
public Triangle(int x,int y,int z){
a=x; b=y; c=z;
}
Triangle(){;} //改动
public String toString() {
return "("+a+","+b+","+c+")";
}
}
class DengYao extends Triangle{
public DengYao(int x,int y){
super(x,x,y);
}
public DengYao() {;} //改动
}
class DengBian extends DengYao{
// public DengBian(int x) {
// super(x,x);
// }
int x;
public DengBian(int y) { //改动
x=y;
}
}
class APP{
public static void main(String [] args) {
Triangle i = new Triangle(3,4,5);
DengYao j = new DengYao(6,7);
DengBian k = new DengBian(9);
System.out.print(i+"\n"+j+"\n"+k);
}
}
不可行
//本例掌握:
超类有参构造函数,需借助super主动调用
不得任意给等腰或等边三角加参数,否则,值可能就落不到a、b、c上