Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Just Java Chapter 81 Lecture 4 “Just Java” Chapter 8 – Interfaces and Cloning Chapter 9 – Packages, Visibility and Nested classes."— Presentation transcript:

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

2 Just Java Chapter 82 Interfaces What problem is solved by interfaces? Transport AirplaneCarBicycle Convertible Saloon land()pedal() topDown() fillRearSeat() drive() getMaxMPH()

3 Just Java Chapter 83 Interfaces Where should the refuel() method go ? Transport AirplaneCarBicycle Convertible Saloon land()pedal() topDown() fillRearSeat() drive() getMaxMPH()

4 "Just Java" Chapter 84 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….

5 "Just Java" Chapter 85 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();

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

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

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

9 Bruce Eckel "Thinking in Java"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”

10 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”

11 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.

12 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 }

13 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); }

14 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();

15 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]+ " "); }

16 Bruce Eckel "Thinking in Java"16 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 Only A Shallow Clone Is Available for Arrays. If you create a new class you must write code to make that class cloneable But why bother?

17 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); }

18 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; }

19 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; }

20 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

21 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( ) )

22 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; } public String toString() { return Double.toString(balance); }

23 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; }

24 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; }

25 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; }

26 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

27 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)

28 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).

29 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.

30 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; }

31 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; }

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

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

34 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();

35 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"); }

36 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) {

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

38 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(); }

39 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)); }

40 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; }

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

42 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); }

43 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

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

45 Just Java Chapter 945 Packages and Visibility

46 "Just Java" Chapter 9 Page 23546 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; } Access Between Two Classes in the Same Package

47 "Just Java" Chapter 9 Page 23647 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; } Access Between Two Unrelated Classes in Different Packages

48 "Just Java" Chapter 9 Page 23748 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; } Access Between A Parent and Child Class in Different Packages

49 Just Java49 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.

50 Just Java50 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.

51 51 //NestedTopLevelExample.java class Top { int i,j; static class SomeClass { // static makes it top-level nested int k; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); }

52 52 public class NestedTopLevelExample { public static void main(String args[]) { Top myTop = new Top(); Top.SomeClass myObject = new Top.SomeClass(); myObject.foo(); } Output Constructing a Top object Constructing SomeClass Hello

53 Just Java53 Member Classes Member classes (there is no such thing as a 'member‘ interface) This inner class (it's not a top-level class) has no static keyword and can access the members of each object of its outer class. The class 'appears in every instance'.

54 Just Java54 The parent class must declare an instance of an inner class, before it can invoke the inner class methods, assign to data fields (including private ones), and so on. Unlike nested top-level classes, inner classes are not directly part of a package and are not visible outside the class in which they are nested. Inner classes are often used for GUI event handlers.

55 55 // MemberClassExample.java class Top { int i = 33; public class SomeClass { // access the outer object's state. private int k = i; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); SomeClass sc = new SomeClass(); System.out.println(sc.k); }

56 56 public class MemberClassExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Constructing SomeClass 33

57 Just Java57 Local Classes A Local class is an inner class. Typically, a local class is declared within a method. It is not a member of an enclosing class. It is visible only within the block. These classes are used primarily as "adapter classes". For example, a block of code that creates a Button object could use a local class to define a simple implementation of the ActionListener Interface. Then it could instantiate this simple implementation and pass the resulting object to the button's addActionListener method, thereby connecting the button to the "callback" code that is executed when the button is pressed.

58 58 // Local Class example class Top { int i = 33; Top() { System.out.println("Constructing a Top object"); // define a class within a method class Wow { int t; Wow() { System.out.println("Building a Wow"); i = 8; t = 9; } Wow h = new Wow(); System.out.println(" h.t == " + h.t); System.out.println(" i == " + i); }

59 59 public class LocalExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Building a Wow h.t == 9 i == 8

60 Just Java60 An anonymous class is refinement of inner classes. It allows you to combine the definition of the class with the instance allocation. Since it is instantiated in the same expression that defines it, it can only be instantiated once. This is very similar to local classes. When writing a simple adapter class, the choice between a named local class and an unnamed anonymous class typically comes down to a matter of style and code clarity, rather than any difference in functionality. The new class can't have a constructor. Anonymous Classes

61 61 // Anonymous.java interface SmallClass { public void foo(); } class Top { int i = 33; void someMethod(SmallClass s) { s.foo(); } void anotherMethod() { someMethod(new SmallClass() { public void foo() { System.out.println("Really fun"); } }); }

62 Just Java62 Top() { System.out.println("Constructing a Top object"); someMethod(new SmallClass() { public void foo() { System.out.println("Strange but fun"); } }); }


Download ppt "Just Java Chapter 81 Lecture 4 “Just Java” Chapter 8 – Interfaces and Cloning Chapter 9 – Packages, Visibility and Nested classes."

Similar presentations


Ads by Google