内容发布更新时间 : 2024/12/27 11:02:51星期一 下面是文章的全部内容请认真阅读。
class Fiction implements Book{ double price; // 价格 int pages; // 页数
public Fiction(int pages, double price) { this.pages = pages; this.price = price; }
//实现接口方法Info() public void Info() {
System.out.println(\is a fiction, which has \+ pages + \pages,\costs \ } }
//杂志类
class Magazine implements Book { double price; // 价格 int pages; // 页数
String publish_time; // 出版时间 //构造方法
public Magazine(int pages, double price, String publish_time) { this.pages = pages; this.price = price;
this.publish_time = publish_time; }
//实现接口方法Info() public void Info() {
System.out.println(\pages,\costs \+ price + \yuan, and publish once every \+ publish_time + \ } }
//期刊类
class Journal implements Book{ double price; // 价格 int pages; // 页数
String publish_time; // 出版时间
public Journal(int pages, double price, String publish_time) { this.pages = pages; this.price = price;
this.publish_time = publish_time; }
//实现接口方法Info()
public void Info() {
System.out.println(\is a journal, which has \+ pages + \pages,\costs \+ price + \yuan, and publish once every \+ publish_time + \ } }
//课本类
class Textbook implements Book{
String applicable_object; // 适用对象 double price; // 价格 int pages; // 页数
public Textbook(int pages, double price, String applicable_object) { this.pages = pages; this.price = price;
this.applicable_object = applicable_object; }
//实现接口方法Info() public void Info() {
System.out.println(\pages,\applicable_object +\ } }
public class Test {
public static void main(String[] args) { Fiction f = new Fiction(199, 12); f.Info();
Magazine m = new Magazine(3, 30, \ m.Info();
Journal j = new Journal(274, 36, \ j.Info();
Textbook t = new Textbook(187, 10.19, \ t.Info(); } }
3.编写程序实现求三角形、正方形和圆形的面积,要求先设计一个公共的父类,在其中定义求面积的方法,在继承得到各种形状。 解答:
package work08;
//定义一个抽象类
abstract class Shape{
public abstract void area();//定义一个抽象方法 }
//矩形类
class Rectangle extends Shape{ private double height; private double width;
public Rectangle(double height, double width){ this.height = height; this.width = width; }
//重写抽象方法
public void area() {
double s = (height*width);
System.out.println(\所求矩形面积为\ } }
//定义一个圆形类
class Circle extends Shape{ private double r;
public static final double PI = 3.14;
public Circle(double r){ this.r = r; }
//重写抽象方法
public void area() { double s = PI *r*r;
System.out.println(\所求矩形面积为\ } }
//定义一个三角形类
class Triangle extends Shape{ public double a; public double b; public double c;
public Triangle(double a, double b, double c){ this.a = a; this.b = b; this.c = c; }
//重写抽象方法
public void area() { double q = (a+b+c)/2;
double result = q*(q-a)*(q-b)*(q-c); double s = Math.sqrt(result);
System.out.println(\所求矩形面积为\ } }
public class ShapeDemo {
public static void main (String [] args){ Shape rectangle = new Rectangle(8.0, 7.0); Shape circle = new Circle(1.0);
Shape triangle = new Triangle(3.0, 4.0, 5.0); rectangle.area(); circle.area(); triangle.area(); } }