package vendingmachine;
public class Vendingmachine {
int price=80;
int balance=f();
int total;
Vendingmachine()//构造函数:如果有一个成员函数的名字和类的名字完全相同,则在创建这个类的每一个对象的时候会自动调用这个函数-->构造函数,构造函数不能有返回类型
{
total=0;
}
Vendingmachine(int prise)//带参数的构造函数
//重载:一个类里同名但参数表不同的函数构成了重载关系,一个类可以有多个构造函数,只要他们的参数表不同
//创建对象的时候给出不同的参数值,就会调用不同的构造函数
{
this.price=prise;
}
int f()
{
return 10;
}
void setPrise(int prise)
{
this.price=prise;
}
void showPrompt()
{
System.out.println("Welcome");
}
void insertMoney(int amount)
{
balance = balance + amount;
}
void showBalance()
{
System.out.println(balance);
}
void getfood()
{
if ( balance >= price)
System.out.println("Here you are.");
balance = balance - price;
total = total + price;
}
public static void main(String[] args)
{
Vendingmachine vm = new Vendingmachine();
vm.showPrompt();
vm.showBalance();
vm.insertMoney(100);
vm.getfood();
vm.showBalance();
Vendingmachine vm1 = new Vendingmachine(100);
vm1.insertMoney(200);
vm.showBalance();
vm1.showBalance();
System.out.println(vm1.price);//根据参数个数自动选择了调用带参数的构造函数
}
//对象变量是对象的管理者
//在函数中可以直接写成员变量的名字来访问成员变量
//在成员函数内部直接调用自己(this)的其他函数
//定义在函数内部的是本地变量,定义在函数外部的是成员变量
//本地变量的生存期和作用域都是函数内部
//成员变量的生存期是对象的生存期,作用域是类内部的成员函数
//
}