标签:double inter 调用 red stat 引用 ati interface 创建
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
实验内容
一:实验代码
抽象类
public abstract class test { public abstract double S(); }
S三角形
public class term1 extends test { private double a, b, c; public term1(double a, double b, double c) { this.setA(a); this.setB(b); this.setC(c); } public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } public double getP() { double p = ((a + b + c) / 2); return p; } public double S() { double s = Math.sqrt(getP() * (getP() - a) * (getP() - b) * (getP() - c)); return s; } }
S矩形
public class dome2 extends test { public double q, w; public dome2(double q, double w) { this.setQ(q); this.setW(w); } public double getQ() { return q; } public void setQ(double q) { this.q = q; } public double getW() { return w; } public void setW(double w) { this.w = w; } public double S() { double s = q * w; return s; } }
S圆
public class dome3 extends test { public double redius; public dome3(double redius) { this.redius = redius; } public double getRedius() { return redius; } public void setRedius(double redius) { this.redius = redius; } public double S() { double s = Math.pow(redius, 2) * 3.14; return s; } }
测试类
public class test1 { public static void main(String[] args) { term1 g = new term1(9, 10, 11); dome2 h = new dome2(4, 5); dome3 j = new dome3(6); System.out.println("三角形面积:" + g.S()); System.out.println("矩形面积:" + h.S()); System.out.println("圆面积:" + j.S()); } }
二:运行截图
二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
一:实验代码
接口
interface shape { public void size(); }
S圆
class Cricle implements shape { public double redius; public Cricle(double redius) { this.redius = redius; } public double getRedius() { return redius; } public void setRedius(double redius) { this.redius = redius; } public double SSS() { double s = Math.pow(redius, 2) * 3.14; return s; } public void size() { System.out.println("圆的大小为" + SSS()); } }
S直线
class straight implements shape { public double h; public straight(double h) { this.h = h; } public double getH() { return h; } public void setH(double h) { this.h = h; } public double S() { double s = h; return s; } public void size() { System.out.println("直线的大小为" + S()); } }
测试类
public class test2 { public static void main(String[] args) { shape str1 = new Cricle(10); shape str2 = new straight(10); str1.size(); str2.size(); } }
二:运行截图
课程总结:这周学习了object类,还有异常的捕获及处理,还有接口的使用,在java中Object类是所有类的公共父类,
一个类要是没有明显的继承一个类,则肯定是Object的子类。 Object中两个常用方法:public boolean equals(Object obj) (对象比较),
public String toSting() (对象打印时调用)。还有这次做作业学会了自定义包的使用。
标签:double inter 调用 red stat 引用 ati interface 创建
原文地址:https://www.cnblogs.com/duweihhw/p/11663971.html