抽象类
在java中,凡是用abstract修饰的类都是抽象类,凡是用abstract修饰的方法都是抽象的方法。
在抽象类中应该注意几点:
1.抽象类与具体类的关系是一般与特殊的关系,是一种继承与被继承的关系。
2.抽象类中不能定义对象,如果要定义对象可以在其具体子类中定义。抽象类中可以定义零个或多个抽象的方法(必须用abstract修饰),但定义的方法都必须在其里子类具体实现,也可以定义具体的方法。
3.声明抽象方法的语法与声明一般方法不同. 抽象方法的没有像一般方法那样包含在大括号{}中的主体部份,并用分号;来结束.。
4.abstract 不能与final 同时修饰一个类(final修饰的类为最终类不能有子类矛盾),abstract不能和static、private、final或native并列修饰同一方法。
举个例子:定义一个商品的抽象类,商品有名称和价格两个属性,其子类可以有计件商品和计重量的商品。
public abstractclass Goods {
public String name;
publicfloatprice;
publicintnumber;
publicfloatweight;
public Goods(String name,float price ,int number,float weight){
this.name = name;
this.price = price;
this.number = number;
this.weight = weight;
}
public String getName(){
returnthis.name;
}
public float getPrice(){
returnthis.price;
}
//定义一个抽象的方法
publicabstractfloat getTotalprice();
//定义具体的方法
public String toString(){
returnthis.getName()+"/t$"+this.price+"/t";
}
}
计件商品类
publicclass Numbergoods extends Goods{
public Numbergoods(String name,float price,int number){
super(name,price,number,0);
}
//自己特有的方法
publicint getNumber(){
returnthis.number;
}
publicfloat getTotalprice() {
returnthis.price * this.number;
}
}
计重量的商品
publicclass Weightgoods extends Goods {
public Weightgoods(String name,float price,float weight){
super(name,price,0,weight);
}
//自己特有的方法
publicfloat getWeight(){
returnthis.weight;
}
publicfloat getTotalprice() {
returnthis.price * this.weight;
}
}
运行类
publicclass Main {
publicstaticvoid main(String[] args) {
Numbergoods beer = new Numbergoods("beer",1.5f,10);
Weightgoods apples = new Weightgoods("apples",1.0f,2.5f);
System.out.println(beer.toString()+"num: "+beer.getNumber()+" /tTotalprice:"+beer.getTotalprice());
System.out.println(apples.toString()+"weig:"+apples.getWeight()+"/tTotalprice:"+apples.getTotalprice());
}
}
抽象类的优点就是可以代码重复使用,缺点就是只要父类改变了抽象方法(增加一个或减少一个),其子类的代码都必须变动。