Java 类继承,super()的使用

本文通过具体示例介绍如何在Java中实现三角形类及其子类等腰三角形和等边三角形的设计。通过不同构造函数传递参数来初始化各类的属性,并在main函数中创建实例并展示其信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*按要求完成如下类的设计:
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上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值