(一)抽象类的使用
设计一个类层次,定义一个抽象类--形状,其中包括有求形状的面积的抽象方法。 继承该抽象类定义三角型、矩形、圆。 分别创建一个三角形、矩形、圆存对象,将各类图形的面积输出。
注:三角形面积s=sqrt(p(p-a)(p-b)*(p-c)) 其中,a,b,c为三条边,p=(a+b+c)/2
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
package test;
public abstract class Shape {
public abstract double area();
}
class Triangle extends Shape {
private double a,b,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 Triangle (double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double p = (a + b + c);
System.out.println("三角形的面积为:"+Math.sqrt(p * (p - a) * (p - b) * (p - c)));
return 0;
}
}
class Rectangle extends Shape {
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
private double width, height;
public Rectangle (double width, double height) {
this.width = width;
this.height = height;
}
public double area() {
System.out.println("矩形的面积为:"+width * height);
return 0;
}
}
class Circle extends Shape {
private double r;
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public Circle (double r) {
this.r = r;
}
public double area() {
System.out.println("圆形的面积为:"+Math.PI * r * r);
return 0;
}
}
package test;
public class Six {
public static void main (String args[]) {
Shape s[] = new Shape[3];
s[0] = new Triangle(10,20,30);
s[1] = new Rectangle(40,50);
s[2] = new Circle(60);
s[0].area();
s[1].area();
s[2].area();
}
}
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
编程技巧
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
package test;
public interface Shape {
public double size();
}
class Line implements Shape{
double x1,x2,y1,y2;
public Line (double x1, double x2, double y1, double y2) {
this.x1 = x1; this.x2 = x2;
this.y1 = y1; this.y2 = y2;
}
public double size() {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
}
class Circle implements Shape{
double r;
public Circle(double r) {
this.r = r;
}
public double size() {
return Math.PI * r * r;
}
}
package test;
public class Six {
public static void main (String args[]) {
Line l = new Line(10,20,30,40);
Circle c = new Circle(50);
System.out.println("直线的长度:"+l.size());
System.out.println("圆的面积:"+c.size());
}
}
本周学习总结
二、抽象类:
1.是以abstract关键字声明的一个类
2.抽象类不可以被实例化。因为用抽象方法无意义。
3.抽象类必须由其子类覆盖了所有的抽象方法,该子类才可以被实例化,否则这个子类还是抽象类。
接口与类相似点
1.一个接口可以有多个方法。
2.接口文件保存在 .java 结尾的文件中,文件名使用接口名。
3.接口的字节码文件保存在 .class 结尾的文件中。
接口与类的区别
1.接口不能用于实例化对象。
2.接口没有构造方法。
3.接口中所有的方法必须是抽象方法。
4.接口支持多继承。
5.接口不是被类继承了,而是要被类实现。
6.接口不能包含成员变量,除了 static 和 final 变量。