读书笔记(第二十一讲)abstract class

来源:互联网 发布:淘宝房产司法拍卖入口 编辑:程序博客网 时间:2024/06/06 04:29

这讲主要讲述了抽象类abstract class,抽象类的一个特点就是不能实例化。不能用new 关键字生成对象。否则编译的时候将出现错误,错误的提示也比较明显。
抽象类中也会有抽象方法abstract method在抽象方法中,特点是有声明,无实现。
抽象类与抽象方法之间的关系是:含有abstract method的class 要声明为abstract class,而abstract class中能有抽象方法与具体方法(有声明有实现)。抽象方法只能存在于抽象类中。
以上是抽象类的一些基本知识。

对于抽象类的继承,相于来说要复杂一些,子类若不是抽象类,则要实现抽象类中的所有抽象方法。
抽象类的好处可以用下面的实例说明:
public class Test2
{
public static void main(String[] args)
{
Shape shape=new Triangle(3,4);
System.out.println(shape.computeArea());

shape=new Rectangle(3,4);
System.out.println(rect.computeArea());



}
}
abstract class Shape
{
public abstract int computeArea();
}


class Triangle extends Shape
{
int width;
int height;
public Triangle(int width,int height)
{
this.width=width;
this.height=height;
}
public int computeArea()
{
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 computeArea()
{
return width*height;
}
}

原创粉丝点击