抽象类

抽象类的应用场景:
    我们在描述一类事物的时候,发现该种事物确实存在着某种行为,但是这种行为目前是不具体的,那么我们可以抽取这种行为 的声明,但是不去实现该种行为,这时候这种行为我们称作为抽象的行为,我们就需要使用抽象类。

抽象类的好处: 强制要求子类一定要实现指定的方法。


抽象类要注意的细节:
    1. 如果一个函数没有方法体,那么该函数必须要使用abstract修饰,把该函数修饰成抽象 的函数。。
    2. 如果一个类出现了抽象的函数,那么该类也必须 使用abstract修饰。
    3. 如果一个非抽象类继承了抽象类,那么必须要把抽象类的所有抽象方法全部实现。
    4. 抽象类可以存在非抽象方法,也可以存在抽象的方法.
    5. 抽象类可以不存在抽象方法的。
    6. 抽象类是不能创建对象的。
        疑问:为什么抽象类不能创建对象呢?
        因为抽象类是存在抽象方法的,如果能让抽象类创建对象的话,那么使用抽象的对象
        调用抽象方法是没有任何意义的。
    7. 抽象类是存在构造函数的,其构造函数是提供给子类创建对象的时候初始化父类的属性的。

abstract不能与以下关键字共同修饰一个方法:
    1. abstract不能与private共同修饰一个方法。 因为抽象方法需要子类来实现,而private修饰的方法不能被继承。
    2. abstract 不能与static共同修饰一个方法。因为抽象方法没有方法体,类名可以直接调用静态方法,无意义。
    3. abstract 不能与final共同修饰一个方法。以为抽象方法需要子类来实现,final修饰的方法不能被重写。

示例代码如下:

 1 abstract class Shape{
 2     String name;
 3     public Shape(String name){
 4         this.name = name;
 5     }
 6     public abstract void getArea();
 7     public abstract void getLength();
 8 }
 9 
10 class Circle extends Shape{
11     double r;
12     public static final double PI = 3.14;
13     public Circle(String name, double r){
14         super(name);
15         this.r = r;
16     }
17     public void getArea(){
18         System.out.println(name+"的面积是:"+PI*r*r);
19     }
20     public void getLength(){
21         System.out.println(name+"的面积是:"+2*PI*r);
22     }
23 }
24 
25 class Rect extends Shape{
26     int width;
27     int height;
28     public Rect(String name, int width, int height){
29         super(name);
30         this.width = width;
31         this.height = height;
32     }
33     public void getArea(){
34         System.out.println(name+"的面积是:"+height*width);
35     }
36     public void getLength(){
37         System.out.println(name+"的面积是:"+2*(height+width));
38     }
39 }
40 
41 class Demo{
42     public static void main(String[] args){
43         Circle c = new Circle("圆形",2.0);
44         c.getArea();
45         c.getLength();
46 
47         Rect r = new Rect("矩形",2,4);
48         r.getArea();
49         r.getLength();
50     }
51 }
View Code
原文地址:https://www.cnblogs.com/nicker/p/6115766.html