实验四 类的继承
实验目的
理解抽象类与接口的使用;
了解包的作用,掌握包的设计方法。
实验要求
掌握使用抽象类的方法。
掌握使用系统接口的技术和创建自定义接口的方法。
了解 Java 系统包的结构。
掌握创建自定义包的方法。
实验内容
(一)抽象类的使用
设计一个类层次,定义一个抽象类--形状,其中包括有求形状的面积的抽象方法。 继承该抽象类定义三角型、矩形、圆。 分别创建一个三角形、矩形、圆存对象,将各类图形的面积输出。
注:三角形面积s=sqrt(p(p-a)(p-b)*(p-c)) 其中,a,b,c为三条边,p=(a+b+c)/2
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
代码如下:
package String;
import java.util.Scanner;
abstract class Shape {
public abstract double Area();
}
class Triangle extends Shape{
private int a,b,c;
public Triangle() {}
public Triangle(int a,int b,int c){
this.a = a;
this.b = b;
this.c = c;
}
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 int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public double Area() {
double p = (a+b+c)/2;
return Math.sqrt(p*(p-getA())*(p-getB())*(p-getC()));
}
}
class Rectangle extends Shape{
private double height,width;
public Rectangle() {}
public Rectangle(double height,double width){
this.height = height;
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double Area() {
return getHeight()*getWidth();
}
}
class Circle extends Shape{
private double radius;
public Circle(){}
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double Area() {
return Math.PI*Math.pow(getRadius(), 2);
}
}
运行截图:
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
编程技巧
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
public interface Shape { //定义接口Shape
public abstract void size();
}
class Straight implements Shape{
private double figure;
public Straight(double figure){ //为属性初始化
this.figure=figure; //为属性赋初始值
}
public void size() { //覆写Shape接口的抽象方法
System.out.println("直线的大小:"+figure);
}
}
class Circle2 implements Shape{ //子类实现Shape接口
private double radious;
public Circle2(double radious){ //为属性初始化
this.radious=radious; //为属性赋初始值
}
public void size() { //覆写Shape接口的抽象方法
System.out.println("圆的面积:"+Math.PI*radious*radious);
}
}
运行截图:
学习总结:
1.abstract的运用
2.强调了抽象方法与接口interface的结合运用
3. 接口中不能包括私有的方法和变量,必要时可使用强制转化
4.抽象方法前必须有abstract修饰