实验四 类的继承
实验目的
·理解抽象类与接口的使用;
·了解包的作用,掌握包的设计方法。
实验要求
·掌握使用抽象类的方法。
·掌握使用系统接口的技术和创建自定义接口的方法。
·了解 Java 系统包的结构。
·掌握创建自定义包的方法。
实验内容
(一)抽象类的使用
设计一个类层次,定义一个抽象类--形状,其中包括有求形状的面积的抽象方法。 继承该抽象类定义三角型、矩形、圆。 分别创建一个三角形、矩形、圆存对象,将各类图形的面积输出。
注:三角形面积s=sqrt(p(p-a)(p-b)*(p-c)) 其中,a,b,c为三条边,p=(a+b+c)/2
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
编程技巧
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
实验源码
package 项目1; public abstract class First { public abstract void getLength(); public abstract void getArea(); }
package 项目1; public class Circle extends First { private double r; public Circle(double r){ this.r=r; } public double getRadius() { return r; } public void setRadius(double r) { this.r = r; } public void getLength() { System.out.println("The circumference of the circle:"+(2*Math.PI*r)); } public void getArea() { System.out.println("The area of the circle:"+(Math.PI*Math.pow(r,2))); } }
package 项目1; public class Rectangle extends First { private double width; private double high; public Rectangle(double width,double high){ this.width=width; this.high=high; } public double getHigh() { return high; } public double getWidth() { return width; } public void setHigh(double high) { this.high = high; } public void setWidth(double width) { this.width = width; } public void getLength() { System.out.println("The circumference of the rectangle:"+2*(width+high)); } public void getArea() { System.out.println("The area of the rectangle:"+width*high); } }
package 项目1; public class Triangle extends First { private double q,w,e; double r; public Triangle(double q,double w,double e){ this.q=q; this.w=w; this.e=e; r=(q+w+e)/2; } public double getA() { return q; } public double getB() { return w; } public double getC() { return e; } public void setA(double q) { this.q = q; } public void setB(double w) { this.w = w; } public void setC(double e) { this.e = e; } public void getLength() { System.out.println("The perimeter of the triangle:"+(q+w+e)); } public void getArea() { System.out.println("The area of the triangle:"+Math.sqrt(r*(r-q)*(r-w)*(r-e))); } }
package 项目1; public class Test { public static void main(String[] args){ First sha1=new Circle(6); First sha2=new Rectangle(2,5); First sha3=new Triangle(6,8,10); sha1.getLength(); sha1.getArea(); sha2.getLength(); sha2.getArea(); sha3.getLength(); sha3.getArea(); } }
实验结果
实验源码
实验结果
第七周周总结
1Object类
2抽象类与接口的关系
3instanceof关键字
对象 instanceof类--> 返回boolean类