抽象与封装

Posted helloworld2019

tags:

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

1.什么是类,什么是对象?

2.如何创建对象?

3.如何在程序中接收控制台的输入?

4.如何从现实世界中抽象出类?

5.构造方法的作用和特点是什么?

6.什么是方法重载?

 

领养宠物并打印宠物信息

Dog:

技术图片
package Animal;

public class Dog {
    private String name = "旺财";
    private int health = 100;
    private String strain = "拉布拉多犬";
    private int love = 0;

    void print() {
        System.out.println("宠物的自白");
        System.out.println("我的名字叫" + this.name + ",健康值是" + health + "和主人的亲密度是" + love + ",我是一只酷酷的" + this.strain);
    }

    // 自动获取内容
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public String getStrain() {
        return strain;
    }

    public void setStrain(String strain) {
        this.strain = strain;
    }

}
View Code

Penguin;

技术图片
package Animal;

public class Penguin {
    private String name = "qq";
    private int health = 100;
    private int love = 0;
    private String sex = "Q崽";

    void print() {
        System.out.println("宠物的自白");
        System.out.println("我的名字叫" + this.name + ",健康值是 " + health + " 和主人的亲密度是" + love + " 性别是" + this.sex);
    }

    // 自动获取内容
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    public int getLove() {
        return love;
    }

    public void setLove(int love) {
        this.love = love;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}
View Code

Test;

技术图片
package Animal;

import java.util.Scanner;

public class Text {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("欢迎来到宠物店!");
        System.out.println("请输入你要领养的宠物的名字:");
        String name;
        int num;
        name = input.next();
        System.out.println("Please choose the strain you like(1.狗狗 2.企鹅)");
        num = input.nextInt();
        if (num == 1) {
            System.out.println("请选择宠物的品种:(1.聪明的拉布多犬 2.酷酷的雪纳瑞)");
            Dog dog = new Dog();// 使用构造
            dog.setName(name);
            System.out.println(dog.getName());
            dog.print();
        } else {
            Penguin pen = new Penguin();
            System.out.println("选择企鹅的性别:1.Q仔 2.Q妹");
            num = input.nextInt();
            if (num == 1)
                pen.setSex("Q仔");
            else
                pen.setSex("Q妹");
            pen.print();
        }
    }
}
View Code

 

以上是关于抽象与封装的主要内容,如果未能解决你的问题,请参考以下文章

Java 封装

Java 封装

Java 封装

Java 封装

Java封装

Java基础:封装