Computer Science NotesChapter 8Page 1 of 19
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:
- To recognize when a group of related information could best be represented as an object.
- To efficiently organize the data fields, methods, and constructors of an object.
- To use objects you create in other programs.
package chap08CircleStuff;
/** The Chap08Circle class models a circle of a given radius
* with a center at given x and y coordinates.
* @authorKevinMirus
*/
publicclassChap08Circle
{
/** the radius of this Circle. */
privatedoubleradius;
/** the coordinates of the center of the circle.*/
privatedoublex_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
*/
publicdouble getRadius()
{
returnradius;
}//end method getRadius()
/** Returns the area of this Chap08Circle.
* @return the area of this Chap08Circle
*/
publicdouble getArea()
{
return Math.PI * radius * radius;
}//end method getArea()
/** Returns the circumference of this Chap08Circle.
* @return the circumference of this Chap08Circle
*/
publicdouble 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
*/
publicdouble getX()
{
returnx_0;
}//end method getX()
/** Returns the y-coordinate of the center of this Chap08Circle.
* @return the y-coordinate of the center of this Chap08Circle
*/
publicdouble getY()
{
returny_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.
*/
publicvoid 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.
*/
publicvoid 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.
*/
publicvoid 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
*/
publicboolean 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.
* @authorKevinMirus
*/
publicclass Chap08UseACircle
{
/** Uses the Chap08Circle class.
* @param args is not used.
*/
publicstaticvoid 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:
- To understand objects and classes, and use classes to model objects. (7.2)
- To use UML graphical notations to describe classes and objects. (7.2)
- To construct objects using constructors. (7.3)
- To access objects via object reference variables. (7.4)
- To define a reference variable using a reference type. (7.4.1)
- To access an objects data and methods. (7.4.2)
- To declare a class and create an object from a class. (7.4.3)
- To assign default values for an object’s data fields. (7.4.4)
- To distinguish between object reference variables and primitive data type variables. (7.4.5)
- To use classes Date, Random, and JFrame in the Java library. (7.5)
- To distinguish between instance and static variables and methods. (7.6)
- To declare private data fields with appropriate get and set methods. (7.7)
- To encapsulate data fields to make classes easy to maintain. (7.8)
- To differentiate between primitive-type arguments and object-type arguments. (7.9)
- To develop methods with object arguments. (7.9)
- 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 error-free 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
- 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 / circle1: Chap07Circle
-radius : / double / -radius : / 5
-x_0 : / double / -x_0 : / 0
-y_0 : / double / -y_0 : / 0
+Chap07Circle( )
+Chap07Circle (newRadius: double)
+Chap07Circle (newRadius: double, x: double, y: double)
+getRadius( ): double / circle2: Chap07Circle
+getArea( ): double / -radius : / 25
+getCircumference( ): double / -x_0 : / 5
+getX( ): double / -y_0 : / 10
+getY( ): double
+setRadius (newRadius: double) / circle3: Chap07Circle
+setX (x: double) / -radius : / 125
+setY (y: double) / -x_0 : / 0
+contains (x: double, y: double); boolean / -y_0 : / 0
+toString ( ): String
circle4: Chap07Circle
-radius : / 0
-x_0 : / 0
-y_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:
- Write the class code for the following UML diagram.
{
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
- Create the UML diagram summarizing the following class code.
publicclass Triangle {
//data fields
doubles1, s2, s3;
Triangle(){
}
Triangle(double l1, double l2, double l3){
s1 = l1;
s2 = l2;
s3 = l3;
}
publicdouble getPerimiter(){
returns1 + s2 + s3;
}
publicdouble 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.
- objectRefVar.dataField references a public data field of the object
- objectRefVar.method(arguments) references a public method of the object
- 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:
- System.out.println("The area of the circle1 object is: " + circle1.getArea());
- 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
- See
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:
- null for a reference type
- 0 for numeric types
- false for Boolean types
- '\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 / The class Date represents a specific instant in time, with millisecond precision.+Date( ) / Constructs a Date object for the current time.
+Date(msSinceTheEpoch: long) / Constructs a Date object for a time of msSinceTheEpoch milliseconds since "the epoch" of January 1, 1970 GMT.
+toString( ): String / Returns a string representing the date and time.
+getTime( ): long / Returns the number of milliseconds since "the epoch" of January 1, 1970 GMT.
+setTime(msSinceTheEpoch: long): void / Sets a Date object to a new time of msSinceTheEpoch milliseconds since "the epoch" of January 1, 1970 GMT.
import java.util.Date;
/**TheDateTesterclassimplementsanapplicationthat
*usestheDateclass.
*@authorKevinMirus
*/
publicclass DateTester
{
/**UsestheDateclass.
*@paramargsisnotused.
*/
publicstaticvoid 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 / An instance of this class is used to generate a stream of pseudorandom numbers.+Random( ) / Constructs a Random object with the current time as its seed.
+Random(seed: long) / Constructs a Random object with the specified seed.
+nextInt( ): int / Returns a random int value.
+nextInt(n: int ): int / Returns a random int value between 0 and n (exclusive).
+nextLong( ): long / Returns a random long value.
+nextDouble( ): double / Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat( ): float / Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean( ): boolean / Returns a random boolean value.
import java.util.Random;
import java.util.Scanner;
/**TheRandomTesterclassimplementsanapplicationthat
*usestheRandomclass.
*@authorKevinMirus
*/
publicclass RandomTester {
/**UsestheRandomclass.
*@paramargsisnotused.
*/
publicstaticvoid 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 383,150,663 1,053,212,435
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
Section 7.5.3: Displaying GUI Components
Examples of Java classes that are used to produce Graphical User Interfaces:
- JFrame
- JButton
- JRadioButton
- JComboBox
- See
- See
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.
importstatic java.lang.Math.*;
publicclass StaticImportTester
{
publicstaticvoid main(String[] args)
{
System.out.println(sqrt(2));
}
} / import java.lang.Math;
publicclass StaticImportTester
{
publicstaticvoid 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
- See
Section 7.7: Visibility Modifiers