面向对象---继承

Posted zxbaoer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象---继承相关的知识,希望对你有一定的参考价值。

package com.jicheng;
//创建一个宠物的父类
public class Pey {
    private String name;
    private int age;
    private String sex;
    private int health;
    private int love;

    //封装
    public void setName(String name){
        this.name = name;
    }
    public  String getName(){
        return this.name;
    }
    public  void setAge(int age){
        this.age = age;
    }
    public  int getAge(){
        return this.age;
    }
    public void setSex(String sex){
        this.sex = sex;
    }
    public String getSex(){
        return this.sex;
    }
    public void setHealth(int health){
        if(health<1||health>100){
            this.health = 60;
            return;
        }
        this.health = health;
    }
    public int getHealth(){
        return this.health;
    }
    public void setLove(int love){
        if(health<1||health>100){
            this.health = 60;
            return;
        }
        this.health = health;
        this.love = love;
    }
    public int getLove(int love){
        return this.love;
    }

    //宠物的自我介绍方法;
    public void print(){
        System.out.println("宠物的自白:");
        System.out.println("我的名字叫"+name+",今年"+age+"岁了,"+"性别是"+sex+",我的健康值为:"+health+",我和主人的亲密度为:"+love);
    }


}


package com.jicheng;
//pey 的子类狗狗类
public class Dog extends Pey {

    public String zhongnei;

    @Override
    public void print() {
        super.print();
        System.out.print("我的种类是:"+zhongnei+"
");

    }
}



package com.jicheng;
//pey的子类企鹅类
public class Penguin extends Pey {
    public int tizhong;

    public void print(){
        super.print();
        System.out.print("我的体重是:"+tizhong+"斤");
    }
}



package com.jicheng;
//测试类
public class Test {
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.setName("多多");
        dog.setAge(2);
        dog.setSex("雌");
        dog.setHealth(92);
        dog.setLove(85);
        dog.zhongnei = "拉布拉多";
        //调用Dog类继承父类的方法
        dog.print();

        //创建企鹅类的对象
        Penguin penguin = new Penguin();
        penguin.setName("小黑");
        penguin.setAge(1);
        penguin.setSex("雌");
        penguin.setHealth(76);
        penguin.setLove(88);
        penguin.tizhong = 6;

        //调取Penguin类方法print();
        penguin.print();
    }

}

技术分享图片

 

以上是关于面向对象---继承的主要内容,如果未能解决你的问题,请参考以下文章

modem代码-面向对象(数据继承)

代码的认爹之路: 面向对象继承

python 面向对象专题:继承

python 面向对象专题:继承

C++作为面向对象语言的三个基本特征:封装,继承和————

Java面向对象继承