抽象类(abstract class):①使用abstract修饰②无法实例化,即无法调用实例化生成一个对象
抽象方法(abstract method):①使用abstract修饰②必须定义在抽象类中
特点总结:
①抽象类既可以包含抽象方法也可以包含具体方法
②包含抽象方法的类是抽象类
③在子类(非抽象类)继承父类(抽象类)的情况下,子类必须要实现所有父类的抽象方法,否则此子类必须定义为抽象类
抽象类的作用:为子类提供一种规范
例子:
public class TestAbstractClass {
public static void main(String[] args){
Shape shape = new Triangle(10,6); //调用子类带参数的构造方法,实现赋值
int area = shape.computeArea(); //调用子类的方法computeArea(),从而得到
返回值即三角形面积的结果
System.out.println("triangle:"+area);
}
}
abstract class Shape{
public abstract int computeArea(); //自己不实现,而是为子类提供一种规范
}
class Triangle extends Shape{
int width; //定义成员变量
int height; //定义成员变量
public Triangle(int width , int height){ //定义子类Triangle的带参数的构造方法
this.width=width; //将构造方法的传递的参数赋值给成员变量的参数
this.height=height; //将构造方法的传递的参数赋值给成员变量的参数
//this表示对对象自己的引用,this.width 表示获得成员变量
}
public int computeArea(){ //定义一个方法
return (width*height)/2; //返回值为三角形面积
}
}