PHP
·
发表于 5年以前
·
阅读量:8294
package shiyan6;
import java.text.DecimalFormat;//调用格式化数字输出
import javax.swing.JOptionPane;//JOptionPane 弹出一个标准的对话框
/*
* 曹永万
*
* 通过点,圆的从结构层次,介绍类的继承,根据注释补写代码;
* 2019.09.15
*
*/
class Point{//父类点的定义
protected int x,y;//定义点的坐标
public Point() {//确定构造函数
setPoint(0,0);
}
public Point(int a,int b) {//构造函数重载 带参数构造函数
setPoint(a,b);
}
public void setPoint(int a,int b) {//初始化a,b
x=a;
y=b;
}
public int getx() {//获得x的坐标
return x;
}
public int gety() {//获得y的坐标
return y;
}
public String toString() {
return "["+x+","+"y"+"]";
}
}
/* 子类元圆的定义*/
class Circle extends Point{//圆类继承父类点类
protected double radius;//定义圆的半径
public Circle(){
setRadius(0); }
public Circle(double r,int a,int b) {
super(a,b);//调用父类的构造函数
setRadius(r);
}
public void setRadius(double r) {
radius=(r>=0.0?r:0.0);
}
public double getRadius() {//获得圆的半径
return radius;
}
public double area() {
return Math.PI*radius*radius;
}
public String toString() {//圆的半径,以及圆心坐标转换成字符输出
return "Center="+"["+x+","+y+"]"+";Radius="+radius;
}
}
public class InheritanceTest{
public static void main(String[] args) {
Point pointRef,p;//声明两点对象
Circle circleRef,c;//声明两点圆对象
String output;//定义一个字符串变量
p=new Point(30,50);//给点对象赋值
c=new Circle(2.7,120,89);//给圆对象赋值
//把点对象和圆对象转换成字符串然后给字符串output赋值
output="Pointp:"+p.toString()+"\nCricle:"+c.toString();
pointRef=c;
output=output+"\n\nCircle c(via poineRef):"+pointRef.toString();
circleRef=(Circle)pointRef;
output=output+"\n\nCircle c(via poineRef):"+circleRef.toString();
DecimalFormat precision2=new DecimalFormat("0.00");
output+="\nAreaofc(via circleRef):"+precision2.format(circleRef.area());
//将圆定义成点对象输出
if(p instanceof Circle) {
circleRef=(Circle)p;
output+="\n\n cast successful ";
}else
output+="\n\n p dose not refer to a Circle ";
//利用对话框输出相关信息
JOptionPane.showConfirmDialog(null, output,"InheritanceTset",JOptionPane.INFORMATION_MESSAGE);
//退出系统
System.exit(0);
}
}