1. 程式人生 > 其它 >小甲魚課後習題:烏龜吃小魚

小甲魚課後習題:烏龜吃小魚

類與物件

用類製造物件

工作空間:File-->Switch Workplace

物件是實體,類是規範。

物件:屬性和服務。

封裝:對資料的操作(即對外提供的服務)將資料包裹起來。

定義類

自動售貨機:

attribute serve price blance total insertmoney getfood hello VendingMachine


public class VendingMachine {

int price = 80;
int balance;
int total;

VendingMachine() {
total = 0;
}

VendingMachine(int price){
this();
this.price = price;
}

public static void main(String[] args) {
VendingMachine vm = new VendingMachine();
vm.hello();
vm.insertmonry(100);
vm.getfood();
vm.showBalance();

VendingMachine vm1 = new VendingMachine();
vm1.insertmonry(200);
vm.showBalance();
vm1.showBalance();
}

void hello() {
System.out.println("Hello!");
}

void insertmonry(int money) {
balance += money;
}

void getfood() {
if(balance>=price) {
balance-=price;
System.out.println("Hers you are!");
}else {
System.out.println("Money is not enough!");
}
}

void showBalance() {
System.out.println(balance);
}

}

物件變數是物件的管理者。

物件操作:使用用點運算子。

成員變數和成員函式

斷點除錯:斷點 debug stepinto stepover

成員變數:類中規定物件具有的變數,生存期為物件,作用域類內部

本地變數:定義在函式內部的變數,生存期與作用域為函式。

成員函式:函式通過物件呼叫。

this:函式中一個特殊的本地變數,表達了呼叫函式的物件。

物件初始化

定義初始化:預設給“0值”,如果有給出數值,或合法的表示式,則按其初始化。

建構函式:函式名與類名相同,無返回值,也沒有void。

函式過載:函式同名但引數表不同。

this():用於呼叫其它建構函式,只能使用一次。