10、抽象类——abstract class

1、抽象类就是在定义类时,使用关键字abstract修饰。

public abstract class Test

2、抽象类不能实例化。也就是说不能使用new出来一个抽象类的对象(实例),这是抽象类的特点

如果定义一个抽象类Test,这样做错误:Test test = new Test();

3、抽象方法(abstract method):使用abstract关键字修饰的方法叫做抽象方法,抽象方法有定义无实现,抽象方法需要定义在抽象类中,相对于抽象方法,之前所定义的方法叫做具体方法(有声明,有实现)。

4、如果一个类包含了抽象方法,那么这个类一定是抽象类;如果某个类是抽象类,那么该类可以包含具体方法(有声明,有实现)。

         如果一个类中包含了抽象方法,那么这个类一定要声明成为abstract class,也就是说,该类一定是抽象类;反之,如果某个类是抽象类,那么该类既可以包含抽象方法,也可以包含具体方法。

5、无论何种情况,只要一个类是抽象类,那么这个类就无法实例化。

6、在子类继承父类(父类是个抽象类)的情况下,那么该子类必须要实现父类中所定义的所有抽象方法;否则,该子类要声明为一个abstract class。

public class AbstractTest
{
     public static void main(String[] args)
     {
         T t = new T(); 
         //这样写是错误的,抽象类不能实例化
     }
}
  
abstract class T
{
     public abstract void run();
     //抽象方法,有声明无实现,就是不能有花括号部分
  
     public void sing()    //具体方法,有声明有实现
     {
         System.out.println( "singing" );
     }
}

7、抽象类的作用,主要是来定义约束与业务框架,参考以下程序:

public class Test
{
       public static void main(String[] args)
       {
             Shape shape = new Triangle( 10 , 5 );
             int area = shape.computerArea();
  
             shape = new Rectangle( 10 , 10 );
             int area1 = shape.computerArea();
       }
}
  
abstract class Shape
{
       public abstract int computerArea(); //计算形状面积
}
  
class Triangle extends Shape
{
       int width;
       int height;
       public Triangle( int width, int height)
       {
             this .width = width;
             this .height = height;
       }
  
       public int computerArea()
       {
               return width * height / 2 ;
       }
}
  
class Rectangle extends Shape
{
       int width;
       int height;
       public Rectangle( int width, int height)
       {
             this .width = width;
             this .height = height;
       }
  
       public int computerArea()
       {
             return width * height;
       }
     
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值