Java Software Solutions

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Interfaces A Java interface is a collection
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Inheritance Inheritance Reserved word protected Reserved word super
Road Map Introduction to object oriented programming. Classes
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.
1 A Sorting Example (a start for Lab 4 problem number 3)
Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
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.
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.
Chapter 2 Object-Oriented Design. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 2-2 Chapter Objectives Review the core concepts underlying.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Appendix B: Object-Oriented Design Java Software Structures: Designing.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Class Library, Formatting, Wrapper Classes, and JUnit Testing
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
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.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
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.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
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.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Enhancing Classes
Chapter 3: Using Methods, Classes, and Objects
Chapter 4: Writing Classes
More Object Oriented Programming
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
Java Classes Aliases & Null & This
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming Review
Classes, Objects and Methods
Outline Creating Objects The String Class The Random and Math Classes
Object-Oriented Design Part 2
Presentation transcript:

Java Software Solutions Chapter 5 Enhancing Classes

References Revisited Object reference variables An object reference variable stores the address of an object. We use the dot operator to invoke an object’s method. The address in the reference variable is used to locate the representation of the object in memory In order to look up the appropriate method so we can invoke that method.

The null Reference A reference variable that does not currently point to an object is called a null reference. An instance variable has a null reference for its value when it is initially declared. If we try to follow a null reference, a NullPointerException is thrown. The identifier null is a reserved word. We can use it to check whether an instance variable currently points to an object.

Checking an Instance Variable If name is an instance variable, we could use the following code to avoid following a null reference: if (name == null) System.out.println(“Invalid name”); else System.out.println(name.length());

The this Reference this is a reserved word that allows an object to refer to itself. Inside a method, the this reference can be used to refer to the currently executing object. if the following code were part of a method called move(): if (this.position == piece2.position) result = false; Then if move() were invoked by bishop1.move(); this would refer to bishop1, but if move() were invoked by bishop2.move(); , this would refer to bishop2.

Another use for this You can also use the keyword this to eliminate the need for different names for instance variables and method parameters. Assume the following method is in a class with instance variables called name, acctNumber, and balance. The assignments would be ambiguous if it were not for the keyword this. public Account(String name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }

Aliases Object reference variables store the address of the object they represent, not the object itself. Thus you must be careful when using assignment statements for objects. Consider the assignments ChessPiece bishop1 = new ChessPiece(); ChessPiece bishop2 = new ChessPiece(); bishop1 and bishop2 now hold the addresses of two different chess pieces, but if we then make the assignment bishop2 = bishop1; Now bishop1 and bishop2 point to (hold the address of) the same chess piece. We can no longer use bishop2 to access the chess piece it originally pointed to. bishop1 and bishop2 are now aliases for one another.

An Implication of Aliases If we have two reference variables that are aliases for the same object and we use one variable to change the state of the object, the state is also changed for the other variable since there is really only one object. In the previous example, if you use bishop1 to change the board position of bishop1, the board position of bishop2 also is changed. We need to be careful since inadvertent creation of aliases can produce unexpected and undesirable consequences.

Another Implication of Aliases With primitive data, the == operator works as expected to compare two values for equality. But with objects, == returns true only if the two reference variables being compared are aliases of each other. Every object has a method called equals() obtained by inheritance from the object class. But unless you specifically create the equals() method for a specific class (overriding the inherited equals() method), it works just like the == operator. Note: we discuss inheritance in detail in Ch 7.

Additional Comment about equals( ) If you were writing the code for a bishop class, you could include the code for an equals() method that will compare two different bishop objects (such as bishop1 and bishop2) to see if they have advanced to the same row (your condition for equality) on the chess board. It would be important that during program execution your code doesn’t inadvertently cause bishop1 and bishop2 to become aliases; because if they did, your equals() method would always return true. Since bishop1 and bishop2 would be pointing to the same bishop object.

Garbage When during program executions, an object that has been created no longer has a reference variable with its address, that object can no longer be accessed by the program. As was mentioned on an earlier slide, this could happen due to inadvertent creation of an alias. The object is called garbage since it can no longer serve any useful purpose in the program.

Garbage Collection Java performs automatic garbage collection. When the last reference to an object is lost, the object becomes a candidate for garbage collection. Occasionally, the Java runtime environment makes available the memory allocated to objects that were subsequently marked for garbage collection. In other languages, such as C, the programmer must write code to make this happen.

The finalize() Method If there is something that a programmer wants to accomplish in conjunction with an object being destroyed (garbage collection), the programmer can define a method called finalize() in the object’s class. finalize() takes no arguments and has a void return type. It will be executed by the Java runtime after the object is marked for garbage collection and before it is actually destroyed. finalize() is useful for closing files (discussed in Chapter 8).

Passing Parameters to Methods Java passes all parameters by passing the values in the actual parameters to the invoked method’s formal parameters. Parameter passing is, in effect, assignment statements, assigning to the formal parameters copies of the values stored in the invoking method’s actual parameters. Since the formal parameter holds a separate copy of the value that is passed in, any changes to the formal parameter in the called method have no effect on the actual parameter in the calling method.

Passing Objects as Parameters However, when an object is passed to a method, what is actually passed is the address (reference) to the object. The formal parameter and the actual parameter become aliases for each other. If we change the state of the object through a formal parameter reference inside the method, we are also changing the state of the object referenced by the actual parameter. Because they are the same object.

Changing the Value in a Formal Reference Parameter If we change the address in a formal parameter to make the parameter refer to a different object, the actual parameter will still refer to the original object. Now changes to the state of the object pointed to by the formal parameter will no longer change the state of the object pointed to by the invoking method’s actual parameter. Note: this not the same as using the address of the object to change the original object’s state. See pages 277-281, particularly figure 5.3 on p. 281. The only change that is permanent is the change made to the state of the second parameter.

Instance versus Local Variables Local variables are declared inside a method. They only exist in memory while the method in which they are declared is executing. Once execution of the method ends, the local variables no longer exist. Note: Formal parameters are, in effect, local variables Instance variables are declared in a class, but not inside a method. Each object that is created during program execution has memory space for its own instance variables. See page 285. Parameters are local variables.

Static or Class Variables Another kind of variable, called a static variable or class variable, is shared among all instances of a class. There is only one copy of a static variable for all objects of a class. Therefore, changing the value of a static variable during program execution changes it for all existing objects from that class. Memory for a static variable is established when the class that contains it is referenced for the first time in a program. A local variable in a method cannot be static.

Declaring static Variables The reserved word static is used as a modifier to declare a static variable. private static int count = 0; The above declaration declares a variable named count that is a private, static, integer variable. Constants, which are declared using the final modifier, are also often declared using the static modifier as well. Since the value of constants can’t change, only one copy is needed.

Static Methods In chapter 2, we learned that the methods of the math class are static methods, meaning they can be invoked through the class name. No math object need be instantiated. A method is made static by using the static modifier in the method declaration. The main() method of a Java program must declared with the static modifier. So it can be executed by the interpreter without instantiating an object from the class that contains main().

Restrictions on static Methods Because static methods do not operate in the context of a particular object, they cannot reference instance variables. The compiler will issue an error if a static method attempts to use a nonstatic variable. A static method can, however, reference static variables because static variables exist independent of specific objects. The main() method, therefore, can access only static or local variables.

Wrapper Classes In Java there are primitive types (int, double, etc.) in addition to classes and objects. For each primitive type in Java there exists a corresponding wrapper class defined in the java.lang package. The names of the wrapper classes are mostly the same as those of the corresponding primitive classes, except they begin with an upper case letter. The wrapper classes provide methods related to management of the associated primitive type. See figure 5.4 on page 286 and appendix M.

Wrapper Classes There is a wrapper class in the java.lang package for each primitive type: Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean void Void

static Methods and Constants in Wrapper Classes Wrapper classes contain static methods that can be invoked independent of any instantiated object. The Integer class contains a static method called parseInt() to convert an integer that is stored in a String to its corresponding int value. num = Integer.parseInt(str); Wrapper classes often contain static constants. The Integer class contains two static constants, MIN_VALUE and MAX_VALUE, which hold the smallest and largest int values. Other wrapper classes contain similar static methods and constants.

Nested Classes A class written inside another class is called a nested class. A nested class produces a bytecode file whose name is the name of the enclosing class followed by a $ character followed by the name of the nested class. If a class called Nested is declared inside a class called Enclosing, compiling them will result in two bytecode files called: Enclosing.class and Enclosing$Nested.class

Characteristics of Nested Classes Because it is a member of the enclosing class, a nested class has access to the enclosing class’s instance variables and methods. Even if they are declared as private. However, the enclosing class can directly access data in the nested class only if the data is declared public. It is reasonable to declare the data of a private nested class public because only the enclosing class can get to that data. This is an exception to the normal rule that public data violates encapsulation.

Use of Nested Classes A class should be nested only if it makes sense in the context of the enclosing class. When nesting reinforces the relationship between enclosing and nested classes while simplifying the implementation by allowing direct access to the data. The static modifier can be applied to a class, but only if the class is nested inside another. Like static methods, a static nested class cannot reference instance variables or methods defined in its enclosing class.

Inner Classes A nonstatic nested class is called an inner class. Because it is not static, an inner class is associated with each instance of the enclosing class. An instance of an inner class can exist only within an instance of the enclosing class. No member inside an inner class can be declared as static. Using inner classes with public data should be done only in situations in which the outer class is completely dependent on the inner class for its existence.

Interfaces A Java interface is a collection of constants and abstract methods. An abstract method is a method that does not have an implementation. There is no body. The header of the method, including the parameter list, is simply followed by a semicolon. An interface cannot be instantiated. An abstract method can be preceded by the reserved word abstract, though in interfaces it usually is not (since all methods in an interface are abstract, the word would be redundant). Methods in interfaces have public visibility by default.

Implementing Interfaces When a class implements an interface, the class must implement all of the methods specified by the interface. The class can also have other methods. A class implements an interface by providing method implementations for each of the abstract methods specified in the interface. See pages 294 thru 299 of our text for an interface, a class that implements the interface, and a program that uses the class that implements the interface.

The UML Diagram for an Interface Complexity + getComplexity() : int + setComplexity(int) : void MiniQuiz + main(args: String[]): void 1 Question + getQuestion() : String + getAnswer() : String + answerCorrect(String) : boolean + toString() : String 2

The Comparable interface The Java standard class library contains interfaces as well as classes. The Comparable interface, for example, is defined in the java.lang package and contains only one method, compareTo(). The intention is to provide a common mechanism for comparing one object to another. It is up to the designer of each class to decide what it means for one object of that class to be less than, equal to, or greater than another object of the class.

Using the compareTo() Method One object calls the method and passes another object as a parameter: Example: if (obj1.compareTo(obj2) < 0) System.out.println(“obj1 is less than obj2”); The integer that is returned from the compareTo() method should be negative if obj1 is less than obj2, 0 if they are equal, and positive if obj1 is greater than obj2. It is up to the programmer to implement the compareTo() method.

The Iterator interface The Iterator interface is used by classes that represent a collection of objects. Its methods provide a means of moving through the collection one object at a time. The two primary methods in the Iterator interface are hasNext() which returns a boolean result and next() which returns an object. Another method, remove() , can be used to remove from the collection the object that was most recently returned by the next() method.