INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
Java Software Solutions
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Chapter 5: Enhancing Classes
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter 5: Keyboard I/O & Simple GUI’s Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Primitive Types vs. Reference Types Variables of primitive types hold the values of the primitive types directly. Variables of reference types hold references.
Enhancing classes Visibility modifiers and encapsulation revisited
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Abstract Classes.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
INF 523Q Chapter 5: Enhancing Classes (Examples).
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 7 “Object Oriented Design”
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Chapter 5: Enhancing Classes
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
1 Enhancing Classes  Now we can explore various aspects of classes and objects in more detail  Chapter 5 focuses on: object references and aliases passing.
1 Object-Oriented Design Now we can extend our discussion of the design of classes and objects Chapter 6 focuses on: software development activities determining.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
SEEM Java – Basic Introduction, Classes and Objects.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Designing Classes Chapter 3. Contents Encapsulation Specifying Methods Java Interfaces – Writing an Interface – Implementing an Interface – An Interface.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved April 5, 2006 Method Design & Method Overloading ComS 207: Programming I (in Java) Iowa State University,
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Chapter 7 Object-Oriented Design
Chapter 5: Enhancing Classes
Interfaces November 6, 2006 ComS 207: Programming I (in Java)
Chapter 5: Enhancing Classes
Chapter 5: Enhancing Classes
Chapter 4: Writing Classes
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
More Object Oriented Programming
CSI 1102 Introduction to Software Design
Chapter 4: Writing classes
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 5: Enhancing Classes
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Static is one of the modifiers that determine variable and method characteristics. The static modifier associates a variable or method with its class.
Java Classes Aliases & Null & This
Outline Creating Objects The String Class The Random and Math Classes
Object-Oriented Design Part 2
Presentation transcript:

INF 523Q Chapter 5: Enhancing Classes

2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references and aliasesobject references and aliases passing objects as parameterspassing objects as parameters the static modifierthe static modifier nested classesnested classes interfaces and polymorphisminterfaces and polymorphism

3 References b Recall from Chapter 2 that an object reference holds the memory address of an object b Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1

4 Assignment Revisited b The act of assignment takes a copy of a value and stores it in a variable b For primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2 5

5 Reference Assignment b For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1bishop2 After bishop1bishop2

6 Aliases b Two or more references that refer to the same object are called aliases of each other b One object (and its data) can be accessed using different variables b Aliases can be useful, but should be managed carefully b Changing the object’s state (its variables) through one reference changes it for all of its aliases

7 Garbage Collection b When an object no longer has any valid references to it, it can no longer be accessed by the program b It is useless, and therefore called garbage b Java performs automatic garbage collection periodically, returning an object's memory to the system for future use b In other languages, the programmer has the responsibility for performing garbage collection

Passing Objects to Methods b Parameters in a Java method are passed by value b This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) b Passing parameters is essentially an assignment b When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other

Passing Objects to Methods b What you do to a parameter inside a method may or may not have a permanent effect (outside the method) b See Num.java (page 230) Num.java b See ParameterTester.java (page 228) ParameterTester.java b See ParameterPassing.java (page 226) ParameterPassing.java b Note the difference between changing the reference and changing the object that the reference points to

Num.java b //******************************************************************** b // Num.java Author: Lewis and Loftus b // Represents a single integer as an object. b //******************************************************************** b class Num b { b private int value; b // Sets up the new Num object, storing an initial value. b public Num (int update) b { b value = update; b } b // Sets the stored value to the newly specified value. b public void setValue (int update) b { b value = update; b } b // Returns the stored integer value as a string. b public String toString () b { b return value + ""; } }

ParameterTester.java b //******************************************************************** b // ParameterTester.java Author: Lewis and Loftus b // Demonstrates the effects of passing various types of parameters. b //******************************************************************** b class ParameterTester b { b // Modifies the parameters, printing their values before and after making the changes. b public void changeValues (int f1, Num f2, Num f3) b { b System.out.println ("Before changing the values:"); b System.out.println ("f1\tf2\tf3"); b System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); b f1 = 999; b f2.setValue(888); b f3 = new Num (777); b System.out.println ("After changing the values:"); b System.out.println ("f1\tf2\tf3"); b System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); b }

ParameterPassing.java b //****************************************************************** b // ParameterPassing.java Author: Lewis and Loftus b // Demonstrates the effects of passing various types of parameters. b //****************************************************************** b class ParameterPassing b { b // Sets up three variables (one primitive and two objects) to serve as actual parameters b // to the changeValues method. Prints their values before and after calling the method. b public static void main (String[] args) b { b ParameterTester tester = new ParameterTester(); b int a1 = 111; b Num a2 = new Num (222); b Num a3 = new Num (333); b System.out.println ("Before calling changeValues:"); b System.out.println ("a1\ta2\ta3"); b System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); b tester.changeValues (a1, a2, a3); b System.out.println ("After calling changeValues:"); b System.out.println ("a1\ta2\ta3"); b System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); } }

13 The static Modifier b In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather than through a particular object  For example, the methods of the Math class are static  To make a method static, we apply the static modifier to the method definition  The static modifier can be applied to variables as well b It associates a variable or method with the class rather than an object

14 Static Methods public static int triple (int num) { int result; result = num * 3; return result; } class Helper Because it is static, the method could be invoked as: value = Helper.triple (5);

15 Static Methods b The order of the modifiers can be interchanged, but by convention visibility modifiers come first  Recall that the main method is static; it is invoked by the system without creating an object b Static methods cannot reference instance variables, because instance variables don't exist until an object exists b However, they can reference static variables or local variables

16 Static Variables b Static variables are sometimes called class variables b Normally, each object has its own data space b If a variable is declared as static, only one copy of the variable exists private static float price; b Memory space for a static variable is created as soon as the class in which it is declared is loaded

Static Variables b All objects created from the class share access to the static variable b Changing the value of a static variable in one object changes it for all others b Static methods and variables often work together b See MyClass.java (page 234) MyClass.java b See CountInstances.java (page 233) CountInstances.java

MyClass.java b //****************************************************************** b // MyClass.java Author: Lewis and Loftus b // Demonstrates the use of the static modifier. b //****************************************************************** b b class MyClass b { b private static int count = 0; b // Counts the number of instances created. b public MyClass () b { b count++; b } b // Returns the number of instances of this class that have been created. b public static int getCount () b { b return count; b }

CountInstances.java b //****************************************************************** b // CountInstances.java Author: Lewis and Loftus b // Demonstrates the use of the static modifier. b //****************************************************************** b class CountInstances b { b // Creates several MyClass objects and prints the number of b // objects that were created. b public static void main (String[] args) b { b MyClass obj; b for (int scan=1; scan <= 10; scan++) b obj = new MyClass(); b System.out.println ("Objects created: " + MyClass.getCount()); b }

Nested Classes b In addition to a class containing data and methods, it can also contain other classes b A class declared within another class is called a nested class Outer Class Nested Class

Nested Classes b A nested class has access to the variables and methods of the outer class, even if they are declared private b In certain situations this makes the implementation of the classes easier because they can easily share information b Furthermore, the nested class can be protected by the outer class from external use b This is a special relationship and should be used with care

Nested Classes b A nested class produces a separate bytecode file b If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class b Nested classes can be declared as static, in which case they cannot refer to instance variables or methods b A nonstatic nested class is called an inner class

Interfaces b A Java interface is a collection of abstract methods and constants b An abstract method is a method header without a method body  An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off b An interface is used to formally define a set of methods that a class will implement

Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word None of the methods in an interface are given a definition (body) A semicolon immediately follows each method header

Interfaces b An interface cannot be instantiated b Methods in an interface have public visibility by default b A class formally implements an interface by stating so in the class headerstating so in the class header providing implementations for each abstract method in the interfaceproviding implementations for each abstract method in the interface b If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors.

Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

Interfaces b A class that implements an interface can implement other methods as well b See Speaker.java (page 236) Speaker.java b See Philosopher.java (page 237) Philosopher.java b See Dog.java (page 238) Dog.java b A class can implement multiple interfaces b The interfaces are listed in the implements clause, separated by commas b The class must implement all methods in all interfaces listed in the header

Speaker.java b //****************************************************************** b // Speaker.java Author: Lewis and Loftus b // Demonstrates the declaration of an interface. b //****************************************************************** b interface Speaker b { b public void speak (); b public void announce (String str); b }

Philosopher.java b //****************************************************************** b // Philosopher.java Author: Lewis and Loftus b // Demonstrates the implementation of an interface. b //****************************************************************** b b class Philosopher implements Speaker b { b private String philosophy; b b // Establishes this philosopher's philosophy. b public Philosopher (String philosophy) b { b this.philosophy = philosophy; b } b b // Prints this philosophers's philosophy. b public void speak () b { b System.out.println (philosophy); }

Philosopher.java (cont.) b b // Prints the specified announcement. b public void announce (String announcement) b { b System.out.println (announcement); b } b b // Prints this philosophers's philosophy multiple times. b public void pontificate () b { b for (int count=1; count <= 5; count++) b System.out.println (philosophy); b }

Dog.java b //****************************************************************** b // Dog.java Author: Lewis and Loftus b // Demonstrates the implementation of an interface. b //****************************************************************** b b class Dog implements Speaker b { b // Prints this dog's philosophy. b public void speak () b { b System.out.println ("woof"); b } b b // Prints this dog's philosophy and the specified announcement. b public void announce (String announcement) b { b System.out.println ("woof: " + announcement); b }

Polymorphism via Interfaces b An interface name can be used as the type of an object reference variable Doable obj;  The obj reference can be used to point to any object of any class that implements the Doable interface  The version of doThis that the following line invokes depends on the type of object that obj is referring to: obj.doThis();

Polymorphism via Interfaces b That reference is polymorphic, which can be defined as "having many forms"  That line of code might execute different methods at different times if the object that obj points to changes b See Talking.java (page 240) Talking.java b Note that polymorphic references must be resolved at run time; this is called dynamic binding b Careful use of polymorphic references can lead to elegant, robust software designs

Talking.java b //****************************************************************** b // Talking.java Author: Lewis and Loftus b // Demonstrates the use of an interface for polymorphic references. b //****************************************************************** b class Talking b { b // Instantiates two objects using an interface reference and invokes one of the b // common methods. Then casts the interface reference into a class reference b // to invoke its unique method. b public static void main (String[] args) b { b Speaker current; b current = new Dog(); b current.speak(); b current = new Philosopher ("I think, therefore I am."); b current.speak(); b ((Philosopher) current).pontificate(); b }

Interfaces b The Java standard class library contains many interfaces that are helpful in certain situations  The Comparable interface contains an abstract method called compareTo, which is used to compare two objects  The String class implements Comparable which gives us the ability to put strings in alphabetical order  The Iterator interface contains methods that allow the user to move through a collection of objects easily