# 追问大神-向上转型和向下转型的实现。解决方法(2)

www.MyException.Cn  网友分享于：2013-04-25  浏览：7次

this.setR(r);
System.out.println("成功绘制圆!");
}else {
System.out.println("绘制圆条件不符合!");
}
}

// 重写toString方法
public String toString() {
return "圆的半径: " + this.r + "\n圆的周长：" + this.getPerimter() + "\n圆的面积："
+ this.getArea();
}

// 计算圆的周长
public double getPerimter() {
return 2 * 3.1415926 * r;
}

// 计算圆的面积
public double getArea() {
return r * r * 3.1415926;
}

public double getR() {
return r;
}

public void setR(double r) {
this.r = r;
}

}

package com.syq.test;

public class Rectangle extends Shape {

private double length;
private double wide;

public Rectangle() {
}

public Rectangle(double length, double wide) {
this.setLength(length);
this.setWide(wide);
}

// 计算对角线
public double diagonal() {
return Math.sqrt(length * length + wide * wide);
}

public void draw() {
System.out.println("绘制矩形…………长："+this.getLength()+" 宽："+this.getWide());
}

// 绘制矩形
public void draw(Rectangle rectangle) {
if (this.length > 0 && this.wide > 0) {
this.setLength(length);
this.setWide(wide);
System.out.println("成功绘制矩形!");
} else {
System.out.println("绘制矩形条件不符合!");
}
}

// 计算周长
public double getPerimter() {
return 2 * (this.length + this.wide);
}

// 计算面积
public double getArea() {
return this.wide * this.length;
}

// 重写toString方法
public String toString() {
return "矩形的周长: " + this.getPerimter() + "\n矩形的面积: " + this.getArea()
+ "\n矩形的对角线：" + this.diagonal();
}

public double getLength() {
return length;
}

public void setLength(double length) {
this.length = length;
}

public double getWide() {
return wide;
}

public void setWide(double wide) {
this.wide = wide;
}

}

package com.syq.test;

import java.util.Iterator;

public class TestShape {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];

shapes[0] = new Circle(1);
shapes[1] = new Rectangle(1, 1);
shapes[2] = new Triangle(1, 2, 1);

for (int i = 0; i < shapes.length; i++) {

// 到这步已经可以实现向上转型：父类 父类引用变量 = 子类对象
Shape shape = shapes[i];
shape.draw();