Java继承与多态之abstract类
知识点:
抽象类是Java中的一个特殊类,由关键词abstract修饰
抽象类可以抽象行为标准,这些行为标准由抽象方法表示。行为标准的实现由子类完成。
<abstract> <访问权限> class <类名>{
}//这是一个抽象类~
1.抽象类无法被实例化(不能用new+构造方法生成一个引用值)
或者可以说:抽象类可以声明一个对象,无法创建对象,只能通过子类继承。
2.抽象类可以将声明的对象作为子类的上转型对象来调用被子类继承或重写的方法,及被子类继承或隐藏的变量。
3.抽象类中不要有构造方法(没意义)(见1.1习题)
抽象方法
abstract class Example1{
abstract void Fun();//抽象方法,没有方法体
void Happy(){
System.out.println("我爱吃菠萝")
}//普通方法,有方法体
}
1.抽象方法只能存在于抽象类中
2.子类继承抽象类,则必须重写抽象类中的抽象方法(重写时去掉abstract关键词,否则它也会变成抽象类)
3.abstract只能修饰普通方法,不能和static,final,private关键字一同使用。
习题
1.1通过图形类的计算面积的方法,计算矩形和三角形的面积
Shape.java
/**
* 通过图形类的计算面积的方法,计算矩形和三角形的面积。
*/
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********** Begin **********/
// 将 Shape 类改为抽象类
public abstract class Shape {
public int width; // 几何图形的宽
public int height; // 几何图形的高
/*public Shape(int width, int height) {
//this.width = width;
//this.height = height;
}*/
// 定义一个抽象方法 area(),返回值类型为 double,计算图形的面积
abstract double area();
}
// Rectangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性
class Rectangle extends Shape {
Rectangle(int width,int height){
this.width=width;
this.height=height;
}
// 定义一个有参构造器
// 重写抽象方法 area,计算矩形的面积(高*宽),并将计算结果返回
double area(){
double area=width*height;
return area;
}
}
// Triangle 为矩形类,该类继承 Shape 类,并拥有 Shape 类的属性
class Triangle extends Shape{
Triangle(int width,int height){
this.width=width;
this.height=height;
}
// 定义一个有参构造器
// 重写抽象方法 area,计算三角形的面积(高\*宽/2),并将计算结果返回
double area(){
double area=width*height/2.0;
return area;
}
}
/********** End **********/
Demo.java
public class Demo {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
System.out.println("矩形的面积为:" + rectangle.area());
Triangle triangle = new Triangle(2, 5); // 创建三角形类对象
System.out.println("三角形的面积为:" + triangle.area());
}
}