c#和Java中的抽象类

应用场景:当父类中的方法不知道如何去实现的时候,可以考虑将父类写成抽象类,将方法写成抽象方法。

比如:描述一个图形、圆形、 矩形三个类。不管哪种图形都会具备计算面积与周长的行为,但是每种图形计算的方式不一致而已。

c#中的写法(注意子类重写父类的方法时需要加override关键字):

Java中的写法(注意子类重写父类的方法时不需要加override关键字):

 1 /图形类
 2 abstract class MyShape{ 
 3 
 4     String name;
 5 
 6     public MyShape(String name){
 7         this.name = name;
 8     }
 9 
10     public  abstract void getArea();
11     
12     public  abstract void getLength();
13 }
14 
15 //圆形 是属于图形类的一种
16 class Circle extends MyShape{
17     
18     double r;
19 
20     public static final double PI = 3.14;
21 
22     public Circle(String name,double r){
23         super(name);
24         this.r =r;
25     }
26 
27     public  void getArea(){
28         System.out.println(name+"的面积是:"+PI*r*r);
29     }
30     
31     public  void getLength(){
32         System.out.println(name+"的周长是:"+2*PI*r);
33     }
34 }
54 //矩形 属于图形中的 一种
55 class Rect extends MyShape{
56 
57     int width;
58 
59     int height;
60 
61     public Rect(String name,int width, int height){
62         super(name);
63         this.width = width;
64         this.height = height;
65     }
66 
67     public  void getArea(){
68         System.out.println(name+"的面积是:"+width*height);
69     }
70     
71     public  void getLength(){
72         System.out.println(name+"的周长是:"+2*(width+height));
73     }
74 }
75 
76 class Demo
77 {
78     public static void main(String[] args) 
79     {
82         Circle c = new Circle("圆形",4.0);
83         c.getArea();
84         c.getLength();
85 
86         //矩形
87         Rect r = new Rect("矩形",3,4);
88         r.getArea();
89         r.getLength();
91     }
92 }

c#中抽象类使用说明:

Java中抽象类使用说明:

abstract不能与以下关键字共同修饰一个方法:
1. abstract不能与private共同修饰一个方法。
2. abstract 不能与static共同修饰一个方法。
3. abstract 不能与final共同修饰一个方法。

 

posted on 2018-04-24 21:44  琪琪伤感  阅读(515)  评论(0编辑  收藏  举报