继承和多态

目录

继承

语法规则

protected 关键字 

final 关键字 

多态

向上转型

动态绑定

方法重写

向下转型

super关键字


继承

代码中创建的类, 主要是为了抽象现实中的一些事物(包含属性和方法). 有的时候客观事物之间就存在一些关联关系, 那么在表示成类和对象的时候也会存在一定的关联.
 

public class Animal {     
    public String name;          
    public Animal(String name) {      
        this.name = name;     
    }          
    public void eat(String food) {         
        System.out.println(this.name + "正在吃" + food);     
    } 
}

class Cat {  
    public String name;          
    public Cat(String name) {      
        this.name = name;     
    }          
    public void eat(String food) {         
        System.out.println(this.name + "正在吃" + food);     
    } 
} 

class Bird {  
    public String name;          
    public Bird(String name) {         
        this.name = name;     
    }          
    public void eat(String food) {         
        System.out.println(this.name + "正在吃" + food);     
    }          
    public void fly() {         
        System.out.println(this.name + "正在飞 ︿( ̄︶ ̄)︿");     
    } 
} 
 

可以发现:Animal 和 Cat 以及 Bird 这几个类中存在一定的关联关系

  • 这三个类都具备一个相同的 eat 方法, 而且行为是完全一样的.
  • 这三个类都具备一个相同的 name 属性, 而且意义是完全一样的.
  • 从逻辑上讲, Cat 和 Bird 都是一种 Animal (is - a 语义). 

此时, Animal 这样被继承的类, 我们称为 父类 , 基类超类, 对于像 CatBird 这样的类, 我们称为 子类, 派生类
和现实中的儿子继承父亲的财产类似, 子类也会继承父类的字段和方法, 以达到代码重用的效果.  

语法规则

class 子类 extends 父类 {    

 } 

  • 使用 extends 指定父类.
  • Java 中一个子类只能继承一个父类 (而C++/Python等语言支持多继承).
  • 子类会继承父类的所有 public 的字段和方法.
  • 对于父类的 private 的字段和方法, 子类中是无法访问的.
  • 子类的实例中, 也包含着父类的实例. 可以使用 super 关键字得到父类实例的引用.

继承之后如下

class Animal {     
    public String name; 
    public Animal(String name) {         
        this.name = name;     
    } 
    public void eat(String food) {         
        System.out.println(this.name + "正在吃" + food);     
    } 
} 
class Cat extends Animal {     
     public Cat(String name) {         
        // 使用 super 调用父类的构造方法.          
        super(name);     
    } 
} 
class Bird extends Animal {     
     public Bird(String name) {      
        super(name);     
    }
     public void fly() {         
        System.out.println(this.name + "正在飞 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值