抽象类
在面向对象中,所有的对象都是可以把描绘的,反过来,不能描绘的类,或者说是类里面没有足够的信息来描绘出一个对象,这样的类被称为抽象类。
抽象类注意事项:
- 抽象类不能被实例化,但类的成员变量,局部变量,构造方式等依然存在。
- 抽象类不一定有抽象方法,但有抽象方法的类必定是抽象类。
- 抽象方法只有申明,没有实现,就是不包含任何方法体和参数。
- abstract 关键字只能用于普通方法中,不能用于static方法和构造函数中。
- 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非子类也是一个抽象类。
- 子类重写父类时,必须重写父类所有的抽象方法。
- 使用 abstract 关键字修饰的抽象方法不能使用private修饰,并且抽象方法就是由子类重写的,不然就不能实现重写。
示例:
public class dome2{
public static void main(String[] args) {
Shape s1=new Square(4,5);
s1.shapeprint();
Shape s2=new Triangle(4,3);
s2.shapeprint();
}
}
abstract class Shape{ //父类形状类
int w; //定义形状的高
int l; //定义形状的长
public Shape(int l,int w) {
this.w=w;
this.l=l;
}
public abstract void shapeprint(); //该类是抽象类,子类必须重写
}
class Square extends Shape{ //正方形类
public Square(int l, int w) {
super(l, w);
// TODO Auto-generated constructor stub
}
public void shapeprint() {
System.out.println("正方形的面积是:"+(this.l*this.w));
}
}
class Triangle extends Shape{ //三角形类
public Triangle(int l, int w) {
super(l, w);
// TODO Auto-generated constructor stub
}
public void shapeprint() {
System.out.println("正方形的面积是:"+(this.l*this.w)/2);
}
}
结果
正方形的面积是:20
正方形的面积是:6