标签:a+b ret extend double 抽象 sha 面积 创建 方法
题目:设计一个类层次,定义一个抽象类--形状,其中包括有求形状的面积的抽象方法。 继承该抽象类定义三角型、矩形、圆。 分别创建一个三角形、矩形、圆存对象,将各类图形的面积输出。
注:三角形面积s=sqrt(p*(p-a)*(p-b)*(p-c)) 其中,a,b,c为三条边,p=(a+b+c)/2
抽象类-形状
1 package com.itcast.atd.demo06; 2 3 public abstract class Shape { 4 private String triangle; 5 private String rectangle; 6 private String circle; 7 8 public abstract void shape(); 9 10 }
三角形
1 package com.itcast.atd.demo06; 2 3 public class A extends Shape{//A代表三角形 4 private int a,b,c,p; 5 6 public A(int a, int b, int c, int p) { 7 this.a = a; 8 this.b = b; 9 this.c = c; 10 this.p = p; 11 } 12 13 public int getA() { 14 return a; 15 } 16 17 public void setA(int a) { 18 this.a = a; 19 } 20 21 public int getB() { 22 return b; 23 } 24 25 public void setB(int b) { 26 this.b = b; 27 } 28 29 public int getC() { 30 return c; 31 } 32 33 public void setC(int c) { 34 this.c = c; 35 } 36 37 public int getP() { 38 return (a+b+c)/2; 39 } 40 41 public void setP(int p) { 42 this.p = p; 43 } 44 45 public void shape(){ 46 double s=Math.sqrt(p*(p-a)*(p-b)*(p-c)); 47 System.out.println(s); 48 } 49 }
矩形
package com.itcast.atd.demo06; public class B extends Shape {//B代表矩形 private int a,b; public B(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public void shape(){ double s=a*b; System.out.println(s); } }
圆形
package com.itcast.atd.demo06; public class C extends Shape {//C代表圆形 private double r; public C(double r) { this.r = r; } public double getR() { return r; } public void setR(double r) { this.r = r; } public void shape(){ double s=3.14*Math.pow(r,2); System.out.println(s); } }
测试
package com.itcast.atd.demo06; public class test { public static void main(String[] args) { Shape shape=new A(2,2,2,3); Shape shape1=new B(2,3); Shape shape2=new C(2); shape.shape(); shape1.shape(); shape2.shape(); } }
题目:定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
接口-形状
package com.itcast.atd.demo07; interface Shape{ public abstract void size(); }
直线
package com.itcast.atd.demo07; public class A implements Shape{//A代表直线 private int a=2; @Override public void size() { System.out.println(a); } }
圆形
package com.itcast.atd.demo07; public class B implements Shape {//B代表圆形 private int r=2; @Override public void size() { System.out.println(2*3.14*r); } }
测试
package com.itcast.atd.demo07; public class test { public static void main(String[] args) { A a=new A(); B b=new B(); a.size(); b.size(); } }
标签:a+b ret extend double 抽象 sha 面积 创建 方法
原文地址:https://www.cnblogs.com/changanshisanzhao/p/11648102.html