java中的抽象类

 
 
抽象类
 
在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());
    }  
 
}
抽象类的优点就是可以代码重复使用,缺点就是只要父类改变了抽象方法(增加一个或减少一个),其子类的代码都必须变动。
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值