面向对象与定义类

用类制造对象

对象与类

对象是实体,需要被创建,可以为我们做事情

类是规范,根据类的定义来创建对象

对象

  • 表达东西或事件

  • 运行时响应消息用来提供服务的

  • 定义所有猫的属性

  • 就是java中的类型

  • 可以用来定义变量

对象=属性+服务

数据:属性或状态

操作:函数

 

 把数据和对数据的操作放在一起-->封装

 

定义类

用一个自动售货机来表示

public class Vending {
    //价格
    int price=60;
    //余额
    int balance;
    //所有的钱
    int total;
    void showPrice(){
        System.out.println("你好");
    }
    //计算钱
    void insertMoney(int amount){
        balance = balance+amount;
    }
    //你的余额多少
    void showBalance(){
        System.out.println(balance);
    }
    //买东西
    void getFood(){
        if (balance>=price){
            System.out.println("给你");
            balance = balance-price;
            total = total + price;
        }
    }

    public static void main(String[] args) {
        Vending ve = new Vending();
        ve.showPrice();
        ve.showBalance();
        ve.insertMoney(1000);
        ve.getFood();
    }
}

定义了一个类用new来创建了这个类的一个对象

类是定义了这个类的所有对象长什么样,而对象是这个类的一个个的具体的实例

posted @ 2022-06-10 15:59  魔光领域  阅读(21)  评论(0编辑  收藏  举报