当一个类不知道他的实现方法时就可以抽象出一个类,只给出他的抽象方法,具体实现方法在他的子类中实现。
关键字:abstract
特点: 1、这个类不能够被实例化
2、里面的方法可以不用实现 称为 抽象方法
3、抽象类里面可以有没有实现的方法,也可以有实现了的方法
4、抽象类中可以没有抽象方法
5、有抽象方法的类,必须是抽象类
6、抽象方法,不能使用static和final关键字修饰
要求计算出图形的周长和面积,但是不知道这个图形是什么图形,就可以抽象出一个图形类的方法:
/**图形的抽象类*/
public abstract class Shape {
/**图形类型 type*/
protected String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/**面积的抽象方法*/
public abstract double getArea();
/**周长的抽象方法*/
public abstract double getPerimeter();
}
在子类中实现具体的方法:
/**图形的一个子类--三角形*/
public class Triangle extends Shape{
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
super();
this.type="三角形";
if(this.idTriangle(a, b, c)){
this.a = a;
this.b = b;
this.c = c;
}else{
System.err.println(a+" "+b+" "+c+"不能构成三角形");
}
}
@Override
public double getArea() {
double p=getPerimeter()/2;
double area=Math.sqrt(p*(p-a)*(p-b)*(p-c));
return area;
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
return this.a+this.b+this.c;
}
/**判断a、b、c能否构成一个三角形*/
public static boolean idTriangle(double a,double b,double c){
if(a<=0||b<=0||c<=0){
return false;
}
if(a>b){
a=a+b;
b=a-b;
a=a-b;
}
if(b>c){
b=b+c;
c=b-c;
b=b-c;
}
if(a+b>c){
return true;
}else{
return false;
}
}
}
在main函数中实例化子类:
public static void main(String[] args) {
showArea(new Triangle(3,4,5));
showPerimeter(new Triangle(3,4,5));
}
public static void showArea(Shape shape){
System.out.println(shape.type+"面积:"+shape.getArea());
}
public static void showPerimeter(Shape shape){
System.out.println(shape.type+"周长:"+shape.getPerimeter());
}