JAVA语言程序设计(基础篇) 第十版——第13章 抽象类和接口(参考答案)

编程练习题

13.2~13.3节

**13.1(三角形类)

JAVA语言程序设计(基础篇) 第十版——第13章 抽象类和接口(参考答案)_第1张图片

package p13;

public abstract class GeometricObject {
	private String color;
	private boolean filled;
	private java.util.Date dateCreated;
	
	//构造方法
	protected GeometricObject() {
		dateCreated=new java.util.Date();
	}
	
	//构造方法
	protected GeometricObject(String color, boolean filled) {
	this.color=color;
	this.filled=filled;
	dateCreated=new java.util.Date();
	}
	
	public String getColor() {
		return color;
	
	}
	
	public void setColor(String color) {
		this.color=color;
	}
	
	public boolean isFilled() {
		return filled;
	
	}
	
	public void setFilled(boolean filled) {
		this.filled=filled;
	}
	
	public java.util.Date getDateCreated() {
		return dateCreated;
	
	}
	
	public String toString() {
		return "created on "+dateCreated+"\ncolor: "+color+
		" and filled: "+filled;
	}
	
	public abstract double getArea();
	
	public abstract double getPerimeter();
}

 

package p13;

public class Triangle extends GeometricObject {
	private double side1;
	private double side2;
	private double side3;
	
	public Triangle() {
	
	}
	
	public Triangle(double side1, double side2, double side3) {
		this.side1=side1;
		this.side2=side2;
		this.side3=side3;
	}
	
	public Triangle(double side1, double side2, double side3,
			String color, boolean filled) {
		this.side1=side1;
		this.side2=side2;
		this.side3=side3;
		setColor(color);//调用父类已有方法
		setFilled(filled);//调用父类已有方法
	}
	
	public double getSide1() {
		return side1;
	
	}
	
	public double getSide2() {
		return side2;
	
	}
	
	public double getSide3() {
		return side3;
	
	}
	
	public void setSide1(double side1) {
		this.side1=side1;
	}
	
	public void setSide2(double side2) {
		this.side2=side2;
	}
	
	public void setSide3(double side3) {
		this.side3=side3;
	}
	
	public double getArea() {
		double s=(side1+side2+side3)/2;
		double area=Math.pow( s*(s-side1)*(s-side2)*(s-side3) , 0.5);
		return area;
	}
	
	public double getPerimeter() {
		return side1+side2+side3;
	}
}

 

package p13;

import java.util.Scanner;

public class Test1 {

	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		
		System.out.print("请输入三角形的三条边:");
		double side1=input.nextDouble();
		double side2=input.nextDouble();
		double side3=input.nextDouble();
		
		System.out.print("请输入三角形的颜色:");
		String color=input.next();
		
		System.out.print("该三角形是否填充(true/false):");
		boolean filled=input.nextBoolean();
		
		//创建一个Triangle对象
		GeometricObject object=new Triangle(side1,side2,side3,color,filled);
		
		System.out.println("该三角形的面积为:"+object.getArea());	
		System.out.println("该三角形的周长为:"+object.getPerimeter());
		System.out.println(object.toString());
		
	}

}

JAVA语言程序设计(基础篇) 第十版——第13章 抽象类和接口(参考答案)_第2张图片

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(JAVA编程,java,编程语言)