Download Chapter 8: Objects and Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science Notes
Chapter 8: Objects and Classes
These notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y.
Daniel Lang.
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. To recognize when a group of related information could best be represented as an object.
2. To efficiently organize the data fields, methods, and constructors of an object.
3. To use objects you create in other programs.
package chap08CircleStuff;
public class Chap08Circle
{
/** the radius of this Circle. */
private double radius;
/** the coordinates of the center of the circle.*/
private double x_0, y_0;
/** Constructs a default Chap08Circle object with radius 0
* and centered at (0, 0).
*/
public Chap08Circle ()
{
radius = 0.0;
x_0 = 0.0;
y_0 = 0.0;
}//end constructor Chap08Circle()
/** Constructs a Chap08Circle object of a given radius
* and centered at (0, 0).
* @param newRadius is the desired radius of this Chap08Circle.
*/
public Chap08Circle (double newRadius)
{
radius = newRadius;
x_0 = 0.0;
y_0 = 0.0;
}//end constructor Chap08Circle(double)
/** Constructs a Chap08Circle object of a given radius
* and centered at (x, y).
* @param newRadius is the desired radius of this Chap08Circle
* @param x is the desired x-coordinate of this Chap08Circle
* @param y is the desired y-coordinate of this Chap08Circle
*/
public Chap08Circle (double newRadius, double x, double y)
{
radius = newRadius;
x_0 = x;
y_0 = y;
}//end constructor Chap08Circle(double, double, double)
/** Returns the radius of this Chap08Circle.
* @return the radius of this Chap08Circle
*/
public double getRadius()
{
return radius;
}//end method getRadius()
/** Returns the area of this Chap08Circle.
* @return the area of this Chap08Circle
*/
public double getArea()
{
return Math.PI * radius * radius;
}//end method getArea()
/** Returns the circumference of this Chap08Circle.
* @return the circumference of this Chap08Circle
*/
public double getCircumference()
{
return 2 * Math.PI * radius;
}//end method getCircumference()
/** Returns the x-coordinate of the center of this Chap08Circle.
* @return the x-coordinate of the center of this Chap08Circle
*/
public double getX()
{
return x_0;
}//end method getX()
/** Returns the y-coordinate of the center of this Chap08Circle.
* @return the y-coordinate of the center of this Chap08Circle
*/
public double getY()
{
return y_0;
}//end method getY()
/** Sets the radius of this Chap08Circle to a new radius.
* The new radius will always be nonnegative, regardless of what is entered.
* @param newRadius is the new desired radius of this Chap08Circle.
*/
public void setRadius(double newRadius)
{
radius = Math.abs(newRadius);
}//end method setRadius(double)
/** Sets the x-coordinate of the center of this Chap08Circle to a new value.
* @param x is the new desired x-coordinate of the center of this Chap08Circle.
*/
public void setX(double x)
{
x_0 = x;
}//end method setX(double)
/** Sets the y-coordinate of the center of this Chap08Circle to a new value.
* @param y is the new desired y-coordinate of the center of this Chap08Circle.
*/
public void setY(double y)
{
y_0 = y;
}//end method setY(double)
/** Determines whether a given point is inside this Chap08Circle.
* @param x is the y-coordinate of the given point
* @param y is the y-coordinate of the given point
* @return true if (x, y) is inside the circle (or on its edge) and false if it
isn't
*/
public boolean contains(double x, double y)
{
return ((x - x_0)*(x - x_0) + (y - y_0)*(y - y_0) <= radius*radius);
}//end method contains(double, double)
/** Returns a String representation of this Chap08Circle.
* @return the String representation of this Chap08Circle.
*/
public String toString()
{
String q = "This circle is centered at (" + x_0 + ", " + y_0 + "), "
+ "\n has a radius of " + radius + ", "
+ "\n a circumference of " + getCircumference() + ", "
+ "\n and an area of " + getArea();
return q;
}//end method toString()
}//end class Chap08Circle
package chap08CircleStuff;
/** The Chap08UseACircle class implements an application that
* uses the Chap08Circle class.
* @author Kevin Mirus
*/
public class Chap08UseACircle
{
/** Uses the Chap08Circle class.
* @param args is not used.
*/
public static void main (String[] args)
{
Chap08Circle circle1 = new Chap08Circle(5);
Chap08Circle circle2 = new Chap08Circle(25, 5, 10);
Chap08Circle circle3 = new Chap08Circle(125);
Chap08Circle circle4 = new Chap08Circle();
System.out.println("The radius of the circle1 object is: "
+ circle1.getRadius());
System.out.println("The center of the circle1 object is at: ("
+ circle1.getX() + ", " + circle1.getY() + ")");
System.out.println("The area of the circle1 object is: "
+ circle1.getArea());
System.out.println("\nThe radius of the circle2 object is: "
+ circle2.getRadius());
System.out.println("The center of the circle2 object is at: ("
+ circle2.getX() + ", " + circle2.getY() + ")");
System.out.println("The circumference of the circle2 object is: "
+ circle2.getCircumference());
System.out.println("\nThe information for the circle3 object is: ");
System.out.println(circle3.toString());
System.out.println("\nThe information for the circle4 object is: ");
System.out.println(circle4);
circle1.setRadius(-3);
circle1.setX(12);
circle1.setY(-8);
System.out.println("\nThe new radius of the circle1 object is: "
+ circle1.getRadius());
System.out.println("\nThe information for the circle1 object is: ");
System.out.println(circle1);
if (circle2.contains(-10, -20))
System.out.println("\nThe circle 2 object contains the point (-10, 20).");
else
System.out.println("\nThe circle 2 object DOES NOT contain the point (10, -20).");
circle1 = null;
circle1 = new Chap08Circle(1);
} //end main(String[])
}//end class Chap08UseACircle
Book’s Statement of Skills:
1. To understand objects and classes, and use classes to model objects. (7.2)
2. To use UML graphical notations to describe classes and objects. (7.2)
3. To construct objects using constructors. (7.3)
4. To access objects via object reference variables. (7.4)
5. To define a reference variable using a reference type. (7.4.1)
6. To access an objects data and methods. (7.4.2)
7. To declare a class and create an object from a class. (7.4.3)
8. To assign default values for an object’s data fields. (7.4.4)
9. To distinguish between object reference variables and primitive data type variables. (7.4.5)
10. To use classes Date, Random, and JFrame in the Java library. (7.5)
11. To distinguish between instance and static variables and methods. (7.6)
12. To declare private data fields with appropriate get and set methods. (7.7)
13. To encapsulate data fields to make classes easy to maintain. (7.8)
14. To differentiate between primitive-type arguments and object-type arguments. (7.9)
15. To develop methods with object arguments. (7.9)
16. To store and process objects in arrays. (7.10)
Section 7.1: Introduction
Procedural programming: data and operations on that data are separate, which requires sending data to methods
via a parameter list.
Object-oriented programming: data and operations on that data are stored in a single entity called an object,
which many times eliminates the need for sending data to methods, and allows for more consistent and errorfree operations on the data, and code that is easier to use, re-use, and maintain.
Section 7.2: Defining Classes for Objects
Vocabulary:

Object-oriented programming: programming using objects
o Contrast to: procedural programming, which is what we’ve been doing… writing code in a
step-by step, linear fashion

state of an object: the values stored in its data fields (i.e., its properties)

behavior of an object: the methods that go along with the object

class: a template of the data and methods of an object

object / instance: a specific example of a class existing in memory

instantiation: the act of creating an instance of a class

data field: the information that must be stored to represent the state of an object

method: a block of code that defines a behavior of an object

constructor: a special method that is used to initialize an object

main class: a class containing a main() method. Most classes do not contain a main() method.

UML (Unified Modeling Language) class diagram: a visual representation of a class where the name
of the class, its data fields, and its methods are all summarized as shown below.
Chap07Circle
-radius :
double
-x_0 :
double
-y_0 :
double
+Chap07Circle( )
+Chap07Circle (newRadius: double)
+Chap07Circle (newRadius: double, x: double, y:
double)
circle1: Chap07Circle
-radius :
-x_0 :
-y_0 :
5
0
0
+getRadius( ): double
+getArea( ): double
+getCircumference( ): double
+getX( ): double
+getY( ): double
+setRadius (newRadius: double)
+setX (x: double)
+setY (y: double)
+contains (x: double, y: double); boolean
+toString ( ): String
circle2: Chap07Circle
-radius :
-x_0 :
-y_0 :
25
5
10
circle3: Chap07Circle
-radius :
-x_0 :
-y_0 :
125
0
0
circle4: Chap07Circle
-radius :
-x_0 :
-y_0 :
0
0
0
Section 7.3: Constructors







Constructors can be (and usually are overloaded)
Classes usually define a constructor without arguments (i.e., a no-arg constructor )
Default constructors are provided automatically by the compiler (as a no-arg constructor with no body)
if no constructors are given.
A constructor’s name must match the name of the class
Constructors do not have a return type (not even void)
Constructors are invoked using the new operator when an object is created.
Constructors play the role of initializing objects.
Practice:
1. Write the class code for the following UML diagram.
public class Rectangle
{
double length;
double width;
public Rectangle()
{
length = 0.0;
width = 0.0;
}//end constructor Rectangle()
public Rectangle(double newLength, double newWidth)
{
length = newLength;
width = newWidth;
}//end constructor Rectangle(double, double)
public double getArea()
{
return length * width;
}//end method getArea()
public double getPerimeter()
{
return 2.0 * length + 2.0 * width;
}//end method getPerimeter()
}//end class Rectangle
2. Create the UML diagram summarizing the following class code.
public class Triangle {
//data fields
double s1, s2, s3;
Triangle(){
}
Triangle(double l1, double l2, double l3){
s1 = l1;
s2 = l2;
s3 = l3;
}
public double getPerimiter(){
return s1 + s2 + s3;
}
public double getArea(){
double sp = (s1 + s2 + s3)/2;
return Math.sqrt(sp*(sp-s1)*(sp-s2)*(sp-s3));
}
}
Triangle
s1: double
s2: double
s3: double
Triangle()
Triangle(l1: double, l2: double, l3:double)
getPerimeter(): double
getArea(): double
Section 7.4: Accessing Objects via Reference Variables
Objects, their data fields, and their methods are stored in blocks of memory. We reference the block of memory
for any given object using references variables.
Section 7.4.1: Reference Variables and Reference Types
 A reference variable is a variable used to refer to a specific instance of an object.
 Reference variables are declared with a line of code that has the class name followed by the variables
name:
ClassName objectRefVar;
Chap07Circle circle1;
 A reference type is the class to which a reference variable refers. Any reference variable can refer to
any object of the same reference type (i.e., same class). Example:
Chap07Circle circle1 = new Chap07Circle(5);
Chap07Circle circle2 = new Chap07Circle(1);
circle1 = circle2;
 To create an instance of an object and assign it to a reference variable:
objectRefVar = new ClassName;
circle1 = new Chap07Circle(5);
 To declare a new reference variable, create an instance of an object and assign it to the reference
variable all in one line of code:
ClassName objectRefVar = new ClassName;
Chap07Circle circle1 = new Chap07Circle(5);
 An object reference variable only stores the memory location of a particular instance of an object (and
not the object itself).
 Arrays are really objects in Java…
Section 7.4.2: Accessing an Object’s Data and Methods
 The dot operator (.) is placed after a reference variable to access the (public) data fields and (public)
methods of the object referred to by that variable.
o objectRefVar.dataField references a public data field of the object
o objectRefVar.method(arguments) references a public method of the object
o Example: circle1.setRadius(-3);
 An instance variable is a data field whose value depends on a specific instance of an object.
 An instance method is a method in an object that can only be invoked on a specific instance of an object.
 A calling object is the object on which an instance method is called.
 Sometimes you can create an instance of an object and use one of its methods without assigning the
object to a reference variable. This is called an anonymous object. Example:
o System.out.println("The area of the circle1 object is: " +
circle1.getArea());
o System.out.println("The area of a circle of radius 2 is: " +
new Chap07Circle(2).getArea());
Section 7.4.3: Example: Declaring Classes and Creating Objects
 You can have two classes in one file, but only one of the classes can be a public class, and the name of
the file must match the name of the public class.
 See www.cs.armstrong.edu/liang/intro7e/book/TestCircle1.java
 See www.cs.armstrong.edu/liang/intro7e/book/Circle1.java
Section 7.4.4: Reference Data Fields and the null Value
 Data fields can be of reference types. That is, you can have a reference to another object inside an
object.
 Data fields that do not reference a type get a special value of null. null is a literal value like true or
false.
 Default data field values:
o null for a reference type
o 0 for numeric types
o false for Boolean types
o '\u000' for char types
 Local variables inside a method do not receive default values. You must initialize them yourself.
Section 7.4.5: Differences Between Variables of Primitive Types and Reference Types

The value stored in a primitive type is the actual number stored in the variable.

The value stored in a reference type is a memory location of the object to which it refers.

When a reference type is assigned to a new object, the memory occupied by the old object is “cleaned
up” by the JVM in a process known as garbage collection. That is, the memory is freed and can be re-allocated
as the program continues running.

Tip: if you know that an object is no longer needed, you can assign null to the reference variable for the
object, which will prompt the JVM to perform garbage collection on the space occupied by the object.
Section 7.5: Using Classes from the Java Library
Section 7.5.1: The Date class
java.util.Date
+Date( )
+Date(msSinceTheEpoch: long)
+toString( ): String
+getTime( ): long
+setTime(msSinceTheEpoch: long): void
The class Date represents a specific
instant in time, with millisecond
precision.
Constructs a Date object for the current
time.
Constructs a Date object for a time of
msSinceTheEpoch milliseconds since "the
epoch" of January 1, 1970 GMT.
Returns a string representing the date and
time.
Returns the number of milliseconds since
"the epoch" of January 1, 1970 GMT.
Sets a Date object to a new time of
msSinceTheEpoch milliseconds since "the
epoch" of January 1, 1970 GMT.
import java.util.Date;
/** The DateTester class implements an application that
* uses the Date class.
* @author Kevin Mirus
*/
public class DateTester
{
/** Uses the Date class.
* @param args is not used.
*/
public static void main (String[] args)
{
Date dateNow = new Date();
long tenPIbillion = (long)(Math.PI * 10e9);
Date date2 = new Date(tenPIbillion);
System.out.println("The current Date is: " + dateNow + "\n");
System.out.printf("The number of milliseconds since the epoch " +
"is: \n%,d\n\n", dateNow.getTime());
System.out.println("There are about 10 pi million seconds in a year...");
System.out.println("The date 10 pi billion milliseconds (" +
+ tenPIbillion + ") since the epoch is: \n" + date2);
} //end main(String[])
}//end class DateTester
The current Date is: Tue Mar 02 16:17:05 CST 2010
The number of milliseconds since the epoch is:
1,267,568,225,522
There are about 10 pi million seconds in a year...
The date 10 pi billion milliseconds (31415926535) since the epoch is:
Wed Dec 30 08:38:46 CST 1970
Section 7.5.2: The Random class
java.util.Random
+Random( )
+Random(seed: long)
+nextInt( ): int
+nextInt(n: int ): int
+nextLong( ): long
+nextDouble( ): double
+nextFloat( ): float
+nextBoolean( ): boolean
An instance of this class is used to generate
a stream of pseudorandom numbers.
Constructs a Random object with the current
time as its seed.
Constructs a Random object with the specified
seed.
Returns a random int value.
Returns a random int value between 0 and n
(exclusive).
Returns a random long value.
Returns a random double value between 0.0 and
1.0 (exclusive).
Returns a random float value between 0.0F and
1.0F (exclusive).
Returns a random boolean value.
import java.util.Random;
import java.util.Scanner;
/** The RandomTester class implements an application that
* uses the Random class.
* @author Kevin Mirus
*/
public class RandomTester {
/** Uses the Random class.
* @param args is not used.
*/
public static void main (String[] args)
{
Random random1 = new Random();
Random random2 = new Random(123456789L);
System.out.println("From random1.nextInt():");
for(int i = 1; i <= 5; i++)
System.out.printf("%,15d ",random1.nextInt());
System.out.println();
System.out.println("From random2.nextInt():");
for(int i = 1; i <= 5; i++)
System.out.printf("%,15d ",random1.nextInt());
System.out.println("\n");
System.out.println("From random1.nextInt(100):");
for(int i = 1; i <= 5; i++)
System.out.printf("%4d ",random1.nextInt(100));
System.out.println();
System.out.println("From random2.nextInt(100):");
for(int i = 1; i <= 5; i++)
System.out.printf("%4d ",random1.nextInt(100));
System.out.println();
//Magic eight ball application of the Random class
System.out.println("\n\nAnd now begins your magic eight ball session.");
String[] magicMessages = {"Yes.", "No.", "Maybe.", "Duck.", "Ask later.",
"Today is not your day.", "You have bigger issues to worry
about.",
"WHAT?", "Consider a new shampoo."};
char loopSentinel = 'c';
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter your question for the magic 8 ball:");
String question = keyboard.nextLine();
int messageIndex = random1.nextInt(magicMessages.length);
System.out.println(magicMessages[messageIndex]);
System.out.println("Enter 'y' to continue.");
loopSentinel = keyboard.nextLine().charAt(0);
}while (loopSentinel == 'y');
} //end main(String[])
}//end class RandomTester
From random1.nextInt():
757,864,878 -1,963,420,442
658,922,340
-1,167,001,215
-324,629,752
From random2.nextInt():
-1,112,548,768
-833,577,840
-210,399,819
From random1.nextInt(100):
20
83
66
38
40
From random2.nextInt(100):
1
79
97
53
69
And now begins your magic eight ball session.
Enter your question for the magic 8 ball:
Will Justin pass Com Sci?
Today is not your day.
Enter 'y' to continue.
y
Enter your question for the magic 8 ball:
Where do babies come from?
You have bigger issues to worry about.
Enter 'y' to continue.
y
Enter your question for the magic 8 ball:
Will Obama win the election?
Yes.
Enter 'y' to continue.
n
383,150,663
1,053,212,435
Section 7.5.3: Displaying GUI Components
Examples of Java classes that are used to produce Graphical User Interfaces:

JFrame

JButton

JRadioButton

JComboBox

See www.cs.armstrong.edu/liang/intro7e/book/TestFrame.java

See www.cs.armstrong.edu/liang/intro7e/book/GUIComponents.java
Section 7.6: Static Variables, Constants, and Methods
 An instance variable is a variable in a class whose value is tied to a specific instance of an object of that
class.
 A static variable is a variable in a class that is stored in a common memory location. Thus, its value is
shared by all instances of the class, and so if one object changes the value of the static variables, all
objects see that change.
 Static variables are declared with the keyword modifier static before the variable name.
 Example:
static int numberOFCircleObjects = 0;
 Static variables are underlined in UML diagrams.
 Constants in a class are shared by all objects of the class, and thus they are static variables also. So,
when declare a constant in a class, you need to modify it as final static.
 Example:
final static double PI = 3.1415927;





A static method is a method in a class that can be called without creating an instance of the class.
You call a static method with the name of the class, the dot operator, and the name of the method.
Example: all the methods from the Math class are static methods.
double theta = Math.acos(Math.sqrt(0.5));
Static methods are underlined in UML diagrams.
JDK 1.5 allows you to import static variables and methods directly from a class so that you do not have
to use the class name to reference them.
import static java.lang.Math.*;
public class StaticImportTester
{
public static void main(String[] args)
{
System.out.println(sqrt(2));
}
}



import java.lang.Math;
public class StaticImportTester
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(2));
}
}
In a main class, all methods and variables (that are declared at the class level) must be static.
See www.cs.armstrong.edu/liang/intro7e/book/Circle2.java
See www.cs.armstrong.edu/liang/intro7e/book/TestCircle2.java
Section 7.7: Visibility Modifiers
 Visibility modifiers control access to data fields, methods, and classes.
 The two most common visibility modifiers are public and private.
o public makes data fields, methods, and classes accessible from any class
o private makes data fields and methods accessible from within their own class
o If public or private are not used, then the data fields, methods, and classes are accessible by any
class in the same package. This is known as package-private or package access.
 Packages are used to organize classes. To declare that a class is part of a package, use the following line
of code at the start of the program:
package packageName;
 There is no restriction on accessing methods or data fields from inside the same class.
 If an object is created within an object of the same class, then the parent object has access to all the
private methods of the child object, because they are both of the same class.
 Do not use visibility modifiers on local variables within a method.
 A private constructor prohibits a user of your class from creating an instance of your class. (Used with
classes containing all static methods).
Section 7.8: Data Field Encapsulation
 Data field encapsulation is a standard of object oriented design in which data fields in a class are
declared private.
 A client program is a program that uses a class.
 You should use data field encapsulation because it prevents data in a class from being tampered with.
 You should use data field encapsulation because it prevents clients from setting your data fields to
nonsensical, inconsistent values, which can lead to bugs (unless you write a lot of code to deal with
nonsensical values).
 You should make your data fields private (i.e., encapsulate them) so that outside objects can not change
their values directly.
 If you use data field encapsulation, then you have to provide an “interface” for clients to change the
values of your data fields. This “interface” consists of methods that return the value of a data field and
change the value of a data field (in a consistent manner).
 Accessor methods provide access to the value stored in a data field. The name of an accessor method
starts with get by convention, unless the data field is a Boolean, in which case the method name starts
with is. For example, the getRadius( ) method in the example code is an accessor method. Also,
the contains method could have been called isInteriorPoint( ).
 Mutator methods change the value of a data field (in a consistent manner). The name of a mutator
method starts with set by convention. For example, the setRadius( ) method is a mutator
method.
 See www.cs.armstrong.edu/liang/intro7e/book/Circle3.java
 See www.cs.armstrong.edu/liang/intro7e/book/TestCircle3.java
Section 7.9: Passing Objects to Methods
 You can pass an object to a method.
 As with arrays, passing an object to a method is actually passing the reference of the object to the
method.
 Thus, a method can change public data fields of an object.
 To pass a method, just put the object type followed by a reference variable for the object.
 See www.cs.armstrong.edu/liang/intro7e/book/TestPassObject.java
 Practice: Create a method that determines if two Chap07Circle object intersect.
/**
* Determines whether a given Chap07Circle object intersects this Chap07Circle
object.
* @param circle2 is the given Chap07Circle object
* @return true if the center of circle2 is less than or equal to the sum of the
radii away
*/
public boolean intersects(Chap07Circle circle2)
{
//Compute distance between circle centers.
double centerDistance = Math.sqrt((x_0 - circle2.x_0)*(x_0 - circle2.x_0)
+ (y_0 - circle2.y_0)*(y_0 - circle2.y_0));
return centerDistance <= (radius + circle2.radius);
}//end method intersects(Chap07Circle)
/**
* Determines whether this Chap07Circle completely contains
* a given Chap07Circle object.
* @param circle2 is the given Chap07Circle object.
* @return true if circle2 is completely inside this Chap07Circle.
*/
public boolean contains(Chap07Circle circle2)
{
//Compute distance between circle centers.
double centerDistance = Math.sqrt((x_0 - circle2.x_0)*(x_0 - circle2.x_0)
+ (y_0 - circle2.y_0)*(y_0 - circle2.y_0));
return (centerDistance + circle2.radius) <= radius;
}//end method contains(Chap07Circle)
Section 7.10: Array of Objects
 You can have an array of objects.
 First you must declare the array, and then write a loop to initialize each array element separately.
 See www.cs.armstrong.edu/liang/intro7e/book/TotalArea.java
 Practice: Modify the Chap07UseACircle class to create an array of random circles, then add up their
areas.