java 子类继承父类成员变量的隐藏、实现方法的重写

  成员变量的隐藏和方法的重写

Goods.java

public class Goods {
    public double weight;
    public void oldSetWeight(double w) {
       weight=w;
       System.out.println("double型的weight="+weight);
    }
    public double oldGetPrice() {
        double price = weight*10;
        return price;
    }
}

CheapGoods.java

public class CheapGoods extends Goods {
    public int weight;
    public void newSetWeight(int w) {
       weight=w;
       System.out.println("int型的weight="+weight);
    }
    public double newGetPrice() {
        double price = weight*10;
        return price;
    }
}

Example5_3.java

public class Example5_3 {
  public static void main(String args[]) {
     CheapGoods cheapGoods=new CheapGoods();
     //cheapGoods.weight=198.98; 是非法的,因为子类对象的weight已经是int型
     cheapGoods.newSetWeight(198);
     System.out.println("对象cheapGoods的weight的值是:"+cheapGoods.weight);
     System.out.println("cheapGoods用子类新增的优惠方法计算价格:"+
                         cheapGoods.newGetPrice());
     cheapGoods.oldSetWeight(198.987); //子类对象调用继承的方法操作隐藏的double型变量weight
     System.out.println("cheapGoods使用继承的方法(无优惠)计算价格:"+
                          cheapGoods.oldGetPrice());
  }  
}

 

子类对继承父类方法的重写

University.java

public class University {
    void enterRule(double math,double english,double chinese) {
        double total=math+english+chinese;
        if(total>=180) 
           System.out.println("考分"+total+"达到大学最低录取线");
        else
           System.out.println("考分"+total+"未达到大学最低录取线");
    }
}

ImportantUniversity.java

public class ImportantUniversity extends University{
    void enterRule(double math,double english,double chinese) {
        double total=math+english+chinese;
        if(total>=220)  
           System.out.println("考分"+total+"达到重点大学录取线");
        else
           System.out.println("考分"+total+"未达到重点大学录取线");
    }
}

Example5_4.java

public class Example5_4 {
    public static void main(String args[]) {
       double math=64,english=76.5,chinese=66;
       ImportantUniversity univer = new  ImportantUniversity();
       univer.enterRule(math,english,chinese); //调用重写的方法
       math=89;
       english=80;
       chinese=86;
       univer = new  ImportantUniversity();
       univer.enterRule(math,english,chinese); //调用重写的方法
    }
}

 

转载于:https://www.cnblogs.com/yihujiu/p/5990576.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值