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