前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java——继承遇到构造方法

java——继承遇到构造方法

作者头像
小雨的分享社区
发布2022-10-26 14:44:05
3510
发布2022-10-26 14:44:05
举报
文章被收录于专栏:小雨的CSDN

背景

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

例如, 设计一个类表示动物

代码语言:javascript
复制
class Animal{
    public String name;

    public void eat(){
        System.out.println("Animal::eat()");
    }

    public void sleep(){
        System.out.println("Animal::sleep()");
    }
}

class Cat{
    public String name;

    public void eat(){
        System.out.println("Cat::eat()");
    }
}

class Bird{
    public String name;

    public void eat(){
        System.out.println("Bird::eat()");
    }

    public void fly(){
        System.out.println("Bird::fly()");
    }
}

以上代码可以看出,代码思路虽然没有问题,但是有很多冗余的地方,为了简化代码,我们引出继承

语法规则

class 子类 extends 父类 { }

使用继承之后,代码变成

代码语言:javascript
复制
class Animal{
    public String name;
    public void eat(){
        System.out.println(this.name + "Animal::eat()");
    }
    public void sleep(){
        System.out.println("Animal::sleep()");
    }
}


class Cat extends Animal{
//把以下代码屏蔽,依然可以执行
//    public String name;
//    @Override
//    public void eat(){
//        System.out.println(this.name+"Cat::eat()");
//    }
}

public class TestDemo {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.name = "mimi";
        cat.eat();
    }
}

以上代码的输出结果为:

mimiAnimal::eat()

继承遇到构造方法

由于在给子类构造的时候,要先帮助父类进行构造,利用以下关键字:

super() //必须放到第一行

> super代表父类对象的引用 super():调用父类的构造方法 super.data():访问父类的属性 super.func():访问父类的成员方法

代码修改为:

代码语言:javascript
复制
class Animal{
    public String name;

    //添加构造方法
    public Animal(String name) {
        this.name = name;
    }

    public void eat(){
        System.out.println(this.name + "Animal::eat()");
    }
}

class Cat extends Animal{
    public Cat(String name){
        super(name);//显式调用//写道第一行
    }
//    public String name;
//    @Override
//    public void eat(){
//        System.out.println(this.name+"Cat::eat()");
//    }
}

class Bird extends Animal{
    public Bird(String name){
        super(name);
    }
//    public String name;
//
//    public void eat(){
//        System.out.println("Bird::eat()");
//    }
//
    public void fly(){
        System.out.println("Bird::fly()");
    }
}

public class TestDemo {
    public static void main(String[] args) {
        Cat cat = new Cat("haha");
        cat.eat();
        Bird bird = new Bird("bage");
        bird.eat();//访问Animal的
        bird.fly();//访问自己的
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-11-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 语法规则
  • 继承遇到构造方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档