package objectNextPart;

public class Triang extends Shape {   //继承形状父类
// 定义三角形的三边
private double a, b, c;

public Triang(String color, double a, double b, double c) {
super(color);
this.setSides(a, b, c);
}

public void setSides(double a, double b, double c) {
if (a + b <= c || a + c <= b || b + c <= a) {
System.out.println("三角形的两边之和必须大于第三边");
return;
}
this.a = a;
this.b = b;
this.c = c;

}

// 重写Shape类的计算周长的抽象方法
public double calPerimeter() {
return a + b + c;
}

// 重写Shape类的返回形状的抽象方法
public String getType() {
return getColor() + "三角形";
}
}

//圆类继承Shape父类

public class Circle extends Shape {
private double r;

public Circle(String color, double r) {
super(color);
this.r = r;
}

public double calPerimeter() {
return 2 * Math.PI * r;
}

public String getType() {
return getColor() + "圆形";
}
}

package objectNextPart;  //Shape父类的抽象方法和初始代码块以及成员变量

public abstract class Shape {
{
System.out.println("执行Shape的初始化代码块");
}
private String color;

// 定义一个计算周长的抽象方法
public abstract double calPerimeter();

// 定义一个返回形状的抽象方法;
public abstract String getType();

// 定义Shape的构造器,该构造器并不是用于创建Shape对象
// 而是用于被子类调用
public Shape() {
}

public Shape(String color) {
System.out.println("执行Shape的构造器...");
this.color = color;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

//测试类

public static void main(String[] args) {
Shape s1 = new Triang("黑色", 3, 2, 5);// 执行构造器并设置边长
Shape s2 = new Circle("黄色", 3);
System.out.println(s1.getType());
((Triang) s1).setSides(3, 4, 5);// 重新设置三角形三边并向下强转型
System.out.println(s1.calPerimeter());
System.out.println(s2.getType());
System.out.println(s2.calPerimeter());
}
}