100 likes | 310 Views
Staples are our staple. Building upon our solution. 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 );
E N D
Staples are our staple Building upon our solution
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(); myStapler.punch(); System.out.println( myStapler ); } }
A peek at the gang of three public Object clone() { int n = this.getNumberStaples(); Stapler duplicate = new Stapler(n); return duplicate; }
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); }
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); }
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?
Object passing • Does this satisfy our problem? public void takeStaples(Stapler s) { int n = s.getNumberStaples(); this.addStaples(nl); s.setNumberStaples(0); }
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); }
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); }
Encapsulation • Consider Stapler.java • Consider another Stapler.java • Moral • Practice what you preacb