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; }
} |