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

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Summer A-2000, Project Course-- Carnegie Mellon University 1 Financial Engineering Project Course.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
Mutable, Immutable, and Cloneable Objects Chapter 15.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event.
Inner Classes. Lecture Objectives Learn about inner classes. Know the differences between static and non- static inner classes. Designing and using inner.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
Unit 081 Introduction to Nested Classes Nested classes are classes defined within other classes The class that includes the nested class is called the.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Abstract and Nested Classes
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Programming in Java CSCI-2220 Object Oriented Programming.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Advanced Programming Rabie A. Ramadan vpro/ Lecture 4.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming Java 1 Some Notes on Cloning, Packages and Visibility Notes from Bruce Eckel’s “Thinking in Java” and “Just Java” by.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Carnegie Mellon University, Graduate School of Industrial Administration 1 Initialization and Cloning Slides adapted from course text “Thinking in Java”
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Chapter 3 Implementing Classes
Advanced Programming Practice Questions Advanced Programming. All slides copyright: Chetan Arora.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object Oriented Programming Lecture 2: BallWorld.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 7: Cloning and RTTI
Exceptions, Interfaces & Generics
Chapter 8 Classes and Objects
CompSci 230 S Programming Techniques
Chapter Three - Implementing Classes
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

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

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

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

"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….

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

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

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

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

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”

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 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?

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; } public String 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?

Just Java Chapter 945 Packages and Visibility

"Just Java" Chapter 9 Page 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

"Just Java" Chapter 9 Page 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

"Just Java" Chapter 9 Page 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

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.

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 //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 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

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

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 // 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 public class MemberClassExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Constructing SomeClass 33

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 // 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 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

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

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