Java入门基础学习源码--->类和对象的用法

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)的其他函数
//定义在函数内部的是本地变量,定义在函数外部的是成员变量
//本地变量的生存期和作用域都是函数内部
//成员变量的生存期是对象的生存期,作用域是类内部的成员函数
//
}

转载于:https://www.cnblogs.com/tyhjtz-std/p/5499701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值