第五章

java
继承:学习了继承的实现细节,以及深入继承,还有子类构造方法与父类构造方法的微妙关系,以及继承的意义
继承的实现细节中方法重写:(1)发生在父类和子类之间(2)方法名相同,参数列表相同,返回类型相同(3)子类重写方法的访问权限>=父类被重写的方法

提示:返回类型兼容即可,即不论父类声明的返回类型是什么,子类必须要声明返回一样的类型或该类型的子类
例如实现动物的继承
public class Cat {
  private boolean mammal;//哺乳
     private boolean carnivorous;//食肉
     private int numOfLegs;//几条腿
     private int mood;//情绪
     private String say;//表达方式
    
     //参加私有属性的getter,setter方法
     public boolean isMammal() {
      return mammal;
     }
     public void setMammal(boolean mammal) {
     }
     public boolean isCarnivorous() {
      return carnivorous;
     }
     public void setCarnivorous(boolean carnivorous) {
      this.carnivorous = carnivorous;
     }
     public int getNumOfLegs() {
      return numOfLegs;
     }
     public void setNumOfLegs(int numOfLegs) {
      if(numOfLegs!=4) {
       System.out.println("腿的条数错误!");
          this.numOfLegs = numOfLegs;
      }
     }
     public int getMood() {
      return mood;
     }
     public void setMood(int mood) {
      this.mood = mood;
     }
     public String say() {
   return ("喵喵叫");   
     }
    
     public String say(int mood) {//情绪
   this.setMood(mood); 
   switch(mood) {
   case 1:
    return ("咕噜咕噜叫");
   case 2:
    return ("喵喵叫");
   default:
    return ("摇摇尾巴");
   }
   
     }
  public Cat(){
   this.mammal=true;
   this.carnivorous=true;
   this.numOfLegs=4;
   this.mood=1;
   this.say=say;
  }
}
import javax.swing.plaf.synth.SynthSeparatorUI;
public class TestCat { 
 public static void main(String[] args) {
     Cat Cat=new Cat();
  if(Cat.isMammal()){
      System.out.println("猫是哺乳动物!");
  }else{
      System.out.println("猫是哺乳动物!");
  }
  if(Cat.isCarnivorous()){
      System.out.println("猫是食肉动物!");
        }else{
         System.out.println("猫是食肉动物!");
        }
     System.out.println("一般情况下,猫打招呼的方式是:"+Cat.say());
     System.out.println("猫现在的状态是:"+Cat.say(2));
     System.out.println("猫烦躁打招呼的方式是:"+Cat.say(1));
     System.out.println("猫情绪好时候打招呼的方式是:"+Cat.say(2));
     System.out.println("猫有"+Cat.getNumOfLegs()+"4条腿");
    
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值