java面向对象——继承、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 这几个类中存在一定的关联关系。

此时我们就可以让 Cat 和 Bird 分别继承 Animal 类, 来达到代码重用的效果.

此时, Animal 这样被继承的类, 我们称为 父类 , 基类 或 超类, 对于像 Cat 和 Bird 这样的类, 我们称为 子类, 派生类

语法表示

子类继承父类可以用以下方式表示

class 子类 extends 父类 {

}

如果不想被继承,需要在类前面加上final

final public class Animal {

}

语法规定:

1.子类继承父类,那么子类会包含父类的属性(除构造方法以外的所有)
如果子类要实例化,首先要实例化父类
如果子类要构造,那么需要首先构造父类
2.Java 中一个子类只能继承一个父类
3.子类会继承父类的所有 public 的字段和方法
4.对于父类的 private 的字段和方法, 子类中是无法访问的
5.子类的实例中, 也包含着父类的实例. 可以使用 super 关键字得到父类实例的引用.

super关键字

如果需要在子类内部调用父类方法怎么办? 可以使用super 关键字

public class Bird extends Animal{
    public int age;

   public Bird(String name , int age){
        //构造父类
        super(name);//父类对象的引用
        this.age = age;
    }

    public void fly(){
        System.out.println(this.name + " 正在飞"+"年龄"+this.age);
    }
}

下面是super的其他用法总结

super关键字:代表父类对象的引用
super(): 代表调用父类的构造方法(只能放到第一行)
super.data;代表父类的属性;
super.func(); 代表调用父类的成员方法

superthis有很多相似之处,但是还有一些不同,下面的一个表格来一个对比!
在这里插入图片描述

整体继承代码

public class Animal {
    public String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat(){
        System.out.println(this.name + " 正在吃");
    }
}

public class Dog extends Animal{
    public Dog(String name){
        super(name);
    }
}

public class Bird extends Animal{
    public int age;

   public Bird(String name , int age){
        //构造父类
        super(name);//父类对象的引用
        this.age = age;
    }

    public void fly(){
        System.out.println(this.name + " 正在飞"+"年龄"+this.age);
    }
}

public class TestDemo{
    public static void main(String[] args) {
        Dog dog = new Dog("huahua");
        dog.eat();
        Bird bird =new Bird("bird",2);
        bird.fly();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值