1 / 62

Interfaces and Cloning in Just Java Lecture

This lecture covers the concepts of interfaces and cloning in Java, including how to solve problems using interfaces and the process of cloning objects. It also discusses the use of packages, visibility, and nested classes.

shanice
Download Presentation

Interfaces and Cloning in Just Java Lecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 4 “Just Java” Chapter 8 – Interfaces and Cloning Chapter 9 – Packages, Visibility and Nested classes Just Java Chapter 8

  2. Interfaces What problem is solved by interfaces? Transport getMaxMPH() Airplane Car Bicycle drive() land() pedal() Convertible Saloon topDown() fillRearSeat() Just Java Chapter 8

  3. Interfaces Where should the refuel() method go ? Transport getMaxMPH() Airplane Car Bicycle drive() land() pedal() Convertible Saloon topDown() fillRearSeat() Just Java Chapter 8

  4. Interfaces Where should the refuel() method go? Not in Transport – it would end up in bikes So, perhaps in Airplane and Car. Then we could overload the service method in class SupplyDepot…. "Just Java" Chapter 8

  5. Interfaces Consider the class SupplyDepot… class SupplyDepot { vod service(Car thingToBeServiced){ } void service (Airplane thingToBeServiced) { thingToBeServiced.refuel(); } SupplyDepot depot; : depot.service(myPlane); depot.service(ragTop); depot.service(myCar); thingToBeServiced.refuel(); "Just Java" Chapter 8

  6. But Now We Add JetSki This requires a change to the code in SupplyDepot. Transport getMaxMPH() JetSki Car Bicycle Airplane drive() jumpWake() pedal() land() Convertible Saloon topDown() fillRearSeat() "Just Java" Chapter 8

  7. Use an Interface public interface CapableOfBeingFuelled { public int refuel(); } public class Airplane extends Transport implements CapableOfBeingRefuelled { public int refuel() { purgeWingTanks(); leftTank += this.capacity; } Just Java Chapter 8

  8. SupplyDepot class SupplyDepot { vod service(CapableOfBeingRefuelled thingToBeServiced){ thingToBeServiced.refuel(); } This will take a JetSki as long as JetSki implements CapableOfBeingRefuelled Just Java Chapter 8

  9. Interface An interface is a description of promised behavior. java.lang defines Cloneable, Comparable and Runnable Next we will look at the Cloneable interface. But first, why clone anyway? Notes from Bruce Eckel’s “Thinking in Java” Bruce Eckel "Thinking in Java"

  10. Review Passing Handles • All arguments are passed as handles • You never pass the object itself • Very efficient if – You’re only reading the object – You want to modify the outside object • Sometimes it’s necessary to create a “local” – Changes only affect the local object, not the outside object – Java doesn’t support this directly, but provides “cloning” Bruce Eckel "Thinking in Java"

  11. Making Local Copies In general, you call a method in order to produce a return value and/or a change of state in the object that the method is called for. It is much less common to call a method in order to manipulate its arguments; this is referred to a “calling a method for its side effects”. If you need to modify an argument during a method call and don’t intend to modify the outside argument, then you should protect that argument by making a copy inside your method. Bruce Eckel "Thinking in Java"

  12. Cloning Objects • To produce pass- by- value effect, explicitly clone the object that’s passed to your method. class SomeClass { void f( Sheep x) { x = (Sheep) x. clone(); // Now we have a local sheep object // Any changes to x are private changes } } Bruce Eckel "Thinking in Java"

  13. // A simple Int class class Int { private int i; public Int( int i) { this.i = i; } public void increment() { i++; } public String toString() { return Integer.toString( i); } } Bruce Eckel "Thinking in Java"

  14. public class Cloning { public static void main( String args[]) { Int v[] = new Int[10]; for( int i = 0; i < 10; i++ ) v[i] = new Int(i); for(int i = 0; i < 10; i++) System. out. print("v[" + i + "]=" + v[i]+ " "); System.out.println(); Int v2[] = (Int[]) v. clone(); Bruce Eckel "Thinking in Java"

  15. // Increment all v2's elements: for(int i = 0; i < 10; i++) v2[i].increment(); // See if it changed v's elements: for(int i = 0; i < 10; i++) System. out. print("v[" + i + "]=" + v[i]+ " "); } } Bruce Eckel "Thinking in Java"

  16. Only A Shallow Clone Is Available for Arrays. v[0]=0 v[1]=1 v[2]=2 v[3]=3 v[4]=4 v[5]=5 v[6]=6 v[7]=7 v[8]=8 v[9]=9 v[0]=1 v[1]=2 v[2]=3 v[3]=4 v[4]=5 v[5]=6 v[6]=7 v[7]=8 v[8]=9 v[9]=10 • • If you create a new class you must write code to make that class • cloneable • But why bother? Bruce Eckel "Thinking in Java"

  17. // Forgetting to clone may break encapsulation class BankAccount { private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount ) { balance = balance - amount; } public double getBalance() { return balance; } public String toString() { return Double.toString(balance); } Bruce Eckel "Thinking in Java"

  18. class Customer { private BankAccount account; private String name; public Customer(String aName) { name = aName; account = new BankAccount(0); } public String getName() { return name; } Bruce Eckel "Thinking in Java"

  19. public BankAccount getAccount() { return account; } public void addToAccount(double amt) { account.deposit(amt); } public String toString() { return name + account; } Bruce Eckel "Thinking in Java"

  20. // Anyone can withdraw money! public class CustomerTest { public static void main(String args[]) { Customer joe = new Customer("Joeseph Smith"); BankAccount sureItsPrivate = joe.getAccount(); joe.addToAccount(1000); sureItsPrivate.withdraw(100); System.out.println(joe); } } Joeseph Smith900.0 Bruce Eckel "Thinking in Java"

  21. Adding Clonability to a class • Object. clone( ) is protected so you can’t normally access it • Must override and make it public • Must also implement the Cloneable interface – A flag: interface Cloneable {} // Empty! – Allows you to check it: if( myHandle instanceof Cloneable) // … – Tested by Object. clone( ) • Virtually always call Object.clone( ) in your new clone (via super. clone( ) ) Bruce Eckel "Thinking in Java"

  22. // Allow others to clone objects of class BankAccount class BankAccount implements Cloneable { private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount ) { balance = balance - amount; } public double getBalance() { return balance; } publicString toString() { return Double.toString(balance); } Bruce Eckel "Thinking in Java"

  23. public Object clone() { try { Object clonedAccount = super.clone(); return clonedAccount; } catch(CloneNotSupportedException e) { // can't happen -- we implement cloneable return null; } } } Bruce Eckel "Thinking in Java"

  24. class Customer { private BankAccount account; private String name; public Customer(String aName) { name = aName; account = new BankAccount(0); } public String getName() { return name; } Bruce Eckel "Thinking in Java"

  25. public BankAccount getAccount() { return (BankAccount)account.clone(); } public void addToAccount(double amt) { account.deposit(amt); } public String toString() { return name + account; } } Bruce Eckel "Thinking in Java"

  26. // We can only review Joe's account. // We can change it only through the proper interface. public class CustomerTest { public static void main(String args[]) { Customer joe = new Customer("Joeseph Smith"); BankAccount sureItsPrivate = joe.getAccount(); joe.addToAccount(1000); sureItsPrivate.withdraw(100); System.out.println(joe); } } Joeseph Smith1000.0 Bruce Eckel "Thinking in Java"

  27. The Effect of Object. clone( ) • Copies the bits for the exact object (not just the root class Object) • Should always be the first part of your cloning process (via super. clone( ) ) • Copies the handle values, but not what they’re pointing to (a shallow copy) Bruce Eckel "Thinking in Java"

  28. • To perform a deep copy you must clone the contents • of the handles as well • Once you make clone public, it remains public in derived • classes (the protected trick may only be used once). Bruce Eckel "Thinking in Java"

  29. Be Careful when cloning a class with references. • We can provide a clone method for the Customer class. • We have to remember to clone the account object. Bruce Eckel "Thinking in Java"

  30. class Customer implements Cloneable { private BankAccount account; private String name; public Customer(String aName) { name = aName; account = new BankAccount(0); } public String getName() { return name; } Bruce Eckel "Thinking in Java"

  31. public BankAccount getAccount() { return (BankAccount)account.clone(); } public void addToAccount(double amt) { account.deposit(amt); } public String toString() { return name + "\t" + account; } Bruce Eckel "Thinking in Java"

  32. public Object clone() { try { Object clonedCustomer = super.clone(); ((Customer)clonedCustomer).account = (BankAccount)account.clone(); return clonedCustomer; } Bruce Eckel "Thinking in Java"

  33. catch(CloneNotSupportedException e) { // can't happen we implement // cloneable return null; } } } Bruce Eckel "Thinking in Java"

  34. public class CustomerTest2 { public static void main(String args[]) { Customer list[] = new Customer[3]; Customer list2[]; list[0] = new Customer("Mike"); list[1] = new Customer("Sue"); list[2] = new Customer("Bill"); list2 = (Customer[]) list.clone(); Bruce Eckel "Thinking in Java"

  35. for(int j = 0; j < 3; j++) { list2[j] = (Customer) list[j].clone(); list2[j].addToAccount(100); } for (int j = 0; j < 3; j++) System.out.print(list[j] + "\t"); System.out.println(); for (int j = 0; j < 3; j++) System.out.print(list2[j] + "\t"); } } Bruce Eckel "Thinking in Java"

  36. Inserting Clonability in a derived class class Person {} class Hero extends Person {} class Scientist extends Person implements Cloneable { public Object clone() { try { return super. clone(); } catch (CloneNotSupportedException e) { Bruce Eckel "Thinking in Java"

  37. // This should never happen: // It's Cloneable already! throw new InternalError(); } } } class MadScientist extends Scientist {} Bruce Eckel "Thinking in Java"

  38. public class HorrorFlick { public static void main( String args[]) { Person p = new Person(); Hero h = new Hero(); Scientist s = new Scientist(); MadScientist m = new MadScientist(); // p = (Person) p. clone(); // Compile error // h = (Hero) h. clone(); // Compile error s = (Scientist) s. clone(); m = (MadScientist) m. clone(); } Bruce Eckel "Thinking in Java"

  39. // Snake.java public class Snake implements Cloneable { private Snake next; private char c; // Value of i == number of segments Snake(int i, char x) { c = x; if(--i > 0) next = new Snake(i, (char)(x +1)); } Bruce Eckel "Thinking in Java"

  40. void increment() { c++; if(next != null) next.increment(); } public String toString() { String s = ":" + c; if(next != null) s += next.toString(); return s; } Bruce Eckel "Thinking in Java"

  41. public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) {} return o; } Bruce Eckel "Thinking in Java"

  42. public static void main(String[] args) { Snake s = new Snake(5, 'a'); System.out.println("s = " + s); Snake s2 = (Snake)s.clone(); System.out.println("s2 = " + s2); s.increment(); System.out.println( "after s.increment, s2 = " + s2); } } Bruce Eckel "Thinking in Java"

  43. C:\McCarthy\eckelbook\source\c12>java Snake s = :a:b:c:d:e s2 = :a:b:c:d:e after s.increment, s2 = :a:c:d:e:f Bruce Eckel "Thinking in Java"

  44. Homework Why doesn’t snake.java work properly? What changes would you make to fix it? Bruce Eckel "Thinking in Java"

  45. Packages and Visibility Just Java Chapter 9

  46. Access Between Two Classes in the Same Package package A; public class Foo { int x; void bar() { Example e = new Example(); x = e.i; x = e.j; x = e.k; x = e.l; } } package A; public class Example { public int i; int j; //package protected int k; private int l; } "Just Java" Chapter 9 Page 235

  47. Access Between Two Unrelated Classes in Different Packages package B; import A.*; public class Foo { int x; void bar() { Example e = new Example(); x = e.i; x = e.j; x = e.k; x = e.l; } } package A; public class Example { public int i; int j; //package protected int k; private int l; } "Just Java" Chapter 9 Page 236

  48. Access Between A Parent and Child Class in Different Packages package B; import A.Example; public class Foo extends A.Example { int x; void bar() { Example e = new Example(); x = e.i; x = e.j; x = e.k; x = e.l; x = this.k;//OK! } } package A; public class Example { public int i; int j; //package protected int k; private int l; } "Just Java" Chapter 9 Page 237

  49. Inner Classes • Nested Top Level Classes (not inner) • Member Classes • Local Classes • Anonymous Classes These are used in Java event handling. We will see applications later. Just Java

  50. Nested Top Level Class • Nested top-level classes are not inner classes. • Use as a convenient way to group related classes • Since the class must be static and has no 'this' pointer, it • has no access to the instance data of objects for its • enclosing class. • It behaves just like a 'normal' class or interface. Just Java

More Related