Object and classes Counter public class Counter private
Object and classes
ตวอยาง อานไดเฉพาะเมธอดของคลาส Counter public class Counter{ เทานน เพราะเปน private คอ private int value; ตองเรยกใชตวแปรนผานเมธอดท public void count(){ value = value+1; } คลาส Counter ม เทานน public int get. Value(){return value; } } เรยกวา public class Auser{ … encapsulation Counter tally = new Counter(); Counter tally 02 = new Counter(); tally. count(); int result = tally. get. Value(); //result is set to 2 int result 02 = tally 02. get. Value(); //result 02 is 0, a default value } Instance var มคา default แต local var ตอง initiailize ทกครงนะ
อกตวอยาง Constructor หาม return นะ public class Bank. Account{ private double balance; public Bank. Account(){…} public Bank. Account(double initial. Balance){…} อยาลม initialize ในคอนสตรคเตอร เพราะ null เรยกเมธอดไมไดนะ mutator public void deposit(double amount){…} public void withdraw(double amount){…} public double get. Balance(){…} accessor
Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box 2 = box; box 2 Rectangle X=5 y=10 Width = 20 Height = 30
• หรอจะใชเพอแยก กได เชน instance var กบ local var public Bank. Account(double balance){ this. balance = balance; }
- Slides: 22