Download presentation
Presentation is loading. Please wait.
Published byCordelia Lindsey Modified over 8 years ago
1
Staples are our staple Building upon our solution
2
Why did this program work public class StaplerSimulation{ public static void main(String[] args) { Stapler myStapler = new Stapler(); System.out.println( myStapler ); myStapler.fill(); System.out.println( myStapler ); myStapler.punch(); System.out.println( myStapler ); }
3
A peek at the gang of three public Object clone() { int n = this.getNumberStaples(); Stapler duplicate = new Stapler(n); return duplicate; }
4
Parameterized mutator public void setNumberStaples(int n) { this.numberStaplesLeft = n; } public static void (String[] args) { Stapler myStapler = new Stapler(); myStapler.setNumberStaples(10); System.out.println(myStapler); }
5
Specific construction: tailored configuring // Stapler(): specific constructor public Stapler(int n) { this.setNumberStaples(n); } public static void (String[] args) { Stapler myStapler = new Stapler(10); System.out.println(myStapler); }
6
Object passing Let’s design a method whose parameter is an object variable Consider public void takeStaples(Stapler s) Take staples from s to fill the ‘this’ stapler as much as possible How do we do it?
7
Object passing Does this satisfy our problem? public void takeStaples(Stapler s) { int n = s.getNumberStaples(); this.addStaples(nl); s.setNumberStaples(0); }
8
Take a look Does this satisfy our problem public void takeStaples(Stapler s) { int n = s.getNumberStaples(); this.addStaples(nl); s.setNumberStaples(0); } public static void main(String[] args) { Stapler s1 = new Stapler(); Stapler s2 = new Stapler(); s1.fill(). s2.fill(); s1.takeStaples(s2); }
9
Take a better look public void takeStaples(Stapler s) { int n1 = this.getNumberStaples(); int n2 = s.getNumberStaples(); int total = n1 + n2; n1 = Math.min(this.MAX_NUMBER_STAPLES, total); n2 = total - n1; this.setNumberStaples(n1); s.setNumberStaples(n2); }
10
Encapsulation Consider Stapler.javaStapler.java Consider another Stapler.javaStapler.java Moral Practice what you preacb
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.