博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java新手笔记16 面积
阅读量:4677 次
发布时间:2019-06-09

本文共 1963 字,大约阅读时间需要 6 分钟。

1.图形类

package com.yfs.javase;public class Shape {	//计算面积方法	public double getArea() {		System.out.println("计算面积");		return 0;	}}

 2.圆

package com.yfs.javase;public class Circle extends Shape {		private double r;		public Circle(double r) {		this.r = r;		System.out.println("创建圆形面积");	}		public double getArea() {//覆盖父类的方法		System.out.println("计算圆形面积...");		return 3.14 * r * r;	}}

 3.矩形

package com.yfs.javase;public class Rangton  extends Shape {		private double width;	private double length;		public Rangton(double width, double length) {		this.width = width;		this.length = length;		System.out.println("创建矩形面积");	}		public double getArea() {		System.out.println("计算矩形面积...");		return width * length;	}}

 4.三角形

package com.yfs.javase;public class Trantangle  extends Shape {		private double height;	private double width;		public Trantangle(double height, double width) {		this.height = height;		this.width = width;		System.out.println("创建三角形面积");	}		public double getArea() {		System.out.println("计算三角形面积...");		return 1.0 / 2 * width * height;	}}

 5.测试

package com.yfs.javase;import java.util.Random;public class Test1 {	/**	 * 编写一个图形类,提供计算面积的方法。	 * 通过继承图形类,封装三角形,圆形,正方形类,	 * 覆盖父类的方法。在测试类里随机产生10个图形,	 * 面积求和。	 */	public static void main(String[] args) {		Shape[]  shapes = new Shape[10];//存放子类对象		Random ran = new Random();		double sum = 0;		//创建随即图形		for (int i = 0; i < shapes.length; i++) {			int r = ran.nextInt(101);			if(r > 65) {				shapes[i] = new Circle(ran.nextInt(10));			} else if( r > 35 ){				shapes[i] = new Rangton(ran.nextInt(10),ran.nextInt(10));				//shapes[i].setWidth();			} else {				shapes[i] = new Trantangle(ran.nextInt(10), ran.nextInt(10));			}		}		System.out.println("================");		//计算随机图形面积		for (int i = 0; i < shapes.length; i++) {//			Circle c = (Circle)shapes[i];//			sum += c.getArea();			sum += shapes[i].getArea();//子类对象计算面积		}		System.out.println("sum = " + sum);	}}

 

转载于:https://www.cnblogs.com/feilongblog/p/4675533.html

你可能感兴趣的文章
git 命令图解
查看>>
分布式存储系统可靠性系列三:设计模式
查看>>
this关键字的由来及使用
查看>>
两个时间相差多少 .net中的timespan应用
查看>>
递归 换零钱问题——由打靶子问题引申
查看>>
Python-函数基础
查看>>
Extensible Messaging and Presence Protocol (XMPP) 简介
查看>>
Farm Irrigation
查看>>
windows平板的开发和选型
查看>>
无平方因子的数(数论初步) By ACReaper
查看>>
C语言截取字符串
查看>>
如何查自己的账单
查看>>
JAVA8学习笔记(二)----三个预定义接口
查看>>
JDBC连接各种数据库的字符串
查看>>
构建之法阅读笔记06
查看>>
CentOS minimal新装配置笔记
查看>>
压缩映象原理的一个应用
查看>>
Aurora — 一个在 MSOffice 内输入 LaTeX 公式的很好用插件
查看>>
关于sql优化的一个小总结
查看>>
Java语言中的正则表达式
查看>>