72
Objects and Classes Objects and Classes Writing Your Own Writing Your Own Classes Classes A A review review

Objects and Classes Writing Your Own Classes A review

Embed Size (px)

Citation preview

Page 1: Objects and Classes Writing Your Own Classes A review

Objects and Classes Objects and Classes

Writing Your Own ClassesWriting Your Own Classes

A review A review

Page 2: Objects and Classes Writing Your Own Classes A review

An An object is an object is an abstraction of some entity abstraction of some entitysuch as :such as :

a car, a dog, a flea, a house, or a string of a car, a dog, a flea, a house, or a string of characters.characters.

An An object may be physicalobject may be physical, like a , like a radio, radio,

or intangibleor intangible, like a , like a song.song.

What is an objectWhat is an object??

Page 3: Objects and Classes Writing Your Own Classes A review

Just as a noun is a Just as a noun is a

person, place, or thing; person, place, or thing;

so is an object - so is an object - it is mostly a real word entityit is mostly a real word entity

What is an objectWhat is an object

Page 4: Objects and Classes Writing Your Own Classes A review

I.EI.E. . Attributes(data) and behaviors Attributes(data) and behaviors (methods). (methods).

How is an object is instantiated ?. How is an object is instantiated ?.

Consider the class DiceConsider the class Dice

An Object has An Object has methods & Datamethods & Data

Page 5: Objects and Classes Writing Your Own Classes A review

A Dice class contains A Dice class contains the the attributesattributes ((instance variablesinstance variables))

and the and the behaviorsbehaviors ( (MethodsMethods))

Of a Of a collection of collection of nn six-sided dice. six-sided dice.

Each Dice object has a Each Dice object has a single attribute:single attribute:

an integer an integer ((equal to the number of dice in the collection). equal to the number of dice in the collection).

Page 6: Objects and Classes Writing Your Own Classes A review

The behaviors( methods ) consist of:

A.A. ““rolling the dicerolling the dice” - a method” - a method

B.B. returns the total number of spots displayed returns the total number of spots displayed on the faces of all the dice, ANDon the faces of all the dice, AND

C. C. returns the number of dice returns the number of dice in the collection, ANDin the collection, AND

D. D. changes the number of dice changes the number of dice in the collection. in the collection.

Page 7: Objects and Classes Writing Your Own Classes A review

A A DiceDice object is an abstraction object is an abstraction of a set of of a set of nn dice dice

  

A A DiceDice Class Class

Page 8: Objects and Classes Writing Your Own Classes A review

The Dice class has methods that are available The Dice class has methods that are available to other classes: e.gto other classes: e.g

  // // Create a new Dice objectCreate a new Dice object

Dice d = new Dice();Dice d = new Dice();

// // call a method from the Dice classcall a method from the Dice class to roll to roll the dice the dice

int value = d.rollDice();int value = d.rollDice();

  

A A DiceDice Class Class

Page 9: Objects and Classes Writing Your Own Classes A review

Problem Statement: Problem Statement:

Design a Dice class that models a collection of Design a Dice class that models a collection of nn six-sided dice. six-sided dice.

The class should provide three methods:The class should provide three methods:

int rollDice(), int rollDice(), which simulates tossing the dice and returns the total which simulates tossing the dice and returns the total number of spots displayed on the dice,number of spots displayed on the dice,

int getNumDice(), int getNumDice(), which returns the which returns the number of dice number of dice in the set; andin the set; and

void setNumDice(int n), void setNumDice(int n), which which sets or changes the number of dice.sets or changes the number of dice.

A A DiceDice Class Class

Page 10: Objects and Classes Writing Your Own Classes A review

1.1. import java.util.*; import java.util.*; // for the Random class // for the Random class 

2.2. public class Dicepublic class Dice

3.3. {{

4.4. private int numDice; private int numDice; // Instance variables// Instance variables

5.5. private Random random; private Random random;

6.6.

7.7. public Dice() public Dice() //default constructor -- one die in the set//default constructor -- one die in the set

8.8. { // default constructor has no parameters{ // default constructor has no parameters

9.9. numDice = 1;numDice = 1;

10.10. random = new Random(); random = new Random(); // set up random number generator// set up random number generator

11.11. }}

12.12.

13.13. public Dice(int n) public Dice(int n) // one argument constructor -- n dice in the set// one argument constructor -- n dice in the set

14.14. {{

15.15. numDice = n; numDice = n; // sets the number of dice to “n”// sets the number of dice to “n”

16.16. random = new Random();random = new Random();

17.17. }}

Page 11: Objects and Classes Writing Your Own Classes A review

public int rollDice( ) public int rollDice( )

// Returns the number of spots shown when tossing // Returns the number of spots shown when tossing numDicenumDice dice dice {{17.17. int sum = 0; int sum = 0; 18.18. for (int i = 1; i <= numDice; i++) for (int i = 1; i <= numDice; i++) // for each die in the set// for each die in the set19.19. sum += random.nextInt(6) + 1; sum += random.nextInt(6) + 1; // sum = an integer // sum = an integer

// between 1 and 6, inclusive // between 1 and 6, inclusive20.20. return sum;return sum;21.21. }}

22.22. // setters amd getters methods return values of instance //variables// setters amd getters methods return values of instance //variables23.23. public int getNumDice()public int getNumDice()24.24. {{25.25. return numDice;return numDice;26.26. }}

27.27. public void setNumDice(int n)public void setNumDice(int n)28.28. {{29.29. numDice = n;numDice = n;30.30. }}31.31. }}

Page 12: Objects and Classes Writing Your Own Classes A review

As you declare a String reference:As you declare a String reference:

String s = new String();String s = new String();

you can also declare a Dice reference you can also declare a Dice reference

Dice d = new Dice();Dice d = new Dice();

A A DiceDice Class Class

Page 13: Objects and Classes Writing Your Own Classes A review

Dice contains no main(...) method. Dice contains no main(...) method.

Like the String class, Like the String class,

Dice cannot run independently. Dice cannot run independently.

So you use the Dice class to create a game that uses dice.So you use the Dice class to create a game that uses dice.

What to do with Dice?What to do with Dice?

Page 14: Objects and Classes Writing Your Own Classes A review

Discussion:Discussion:

DiceDice must be saved in a file named must be saved in a file named Dice.javaDice.java..

(public class Dice) (public class Dice) spelled as you declared it.spelled as you declared it.

Java convention dictates that the name of a class begins with an Java convention dictates that the name of a class begins with an uppercase letter. uppercase letter.

All other letters All other letters are lowercaseare lowercase, except those that begin new , except those that begin new words. words.

A A DiceDice Class Class

Page 15: Objects and Classes Writing Your Own Classes A review

The word public is an The word public is an access modifieraccess modifier. .

If a class is specified as If a class is specified as public public

then the then the class can be used by any other class. class can be used by any other class.

Only one public class can be saved in any file. Only one public class can be saved in any file.

Class NamingClass Naming

Page 16: Objects and Classes Writing Your Own Classes A review

Line 4: Line 4: private int numDiceprivate int numDice

The integer variable The integer variable numDice numDice is an is an instance variableinstance variable or or fieldfield

numDice numDice is is visiblevisible to all methods of the class. to all methods of the class.

Any method defined in Dice Any method defined in Dice therefore can use this therefore can use this variable. variable.

A A DiceDice Class - what code does Class - what code does

Page 17: Objects and Classes Writing Your Own Classes A review

Organization of the classOrganization of the class

Page 18: Objects and Classes Writing Your Own Classes A review

numDice numDice is specified as is specified as privateprivate,,

Therefore: Therefore: only the methods of Dice can access or only the methods of Dice can access or modify numDice. modify numDice.

The field The field numDice is not visible outside the Dice class.numDice is not visible outside the Dice class.

Instance variables usually are given Instance variables usually are given private access private access so so outside classes cannot access them directly outside classes cannot access them directly

PRIVATE ACCESSPRIVATE ACCESS

Page 19: Objects and Classes Writing Your Own Classes A review

public access public access specifies that the variable is accessible to all code specifies that the variable is accessible to all code outside the classoutside the class

and a and a variablevariable with with no access modifier no access modifier is accessible to classes is accessible to classes within its package. However, we will look at another modifier within its package. However, we will look at another modifier later.later.

Private Private access dictates that the variable is not visible outside the access dictates that the variable is not visible outside the class.class.

Public access allows all classes inPublic access allows all classes in

Page 20: Objects and Classes Writing Your Own Classes A review

Lines 6-10: Lines 6-10:

public Dice() // the default constructor -- one diepublic Dice() // the default constructor -- one die

{{

numDice = 1;numDice = 1;

}}

The code on lines 6-10 is the class’s The code on lines 6-10 is the class’s default constructordefault constructor. .

The default constructor is like a method but there is The default constructor is like a method but there is no return value, not no return value, not even void. even void.

  

A A DiceDice Class Class

Page 21: Objects and Classes Writing Your Own Classes A review

The name of the The name of the default constructor is the default constructor is the same as the class same as the class name. name.

The default constructor The default constructor creates or instantiates a new object of creates or instantiates a new object of the Dice class, the Dice class,

that is, that is, the default constructor the default constructor allocates memory for each object allocates memory for each object of a class. of a class.

The The access modifier access modifier for the default constructor is for the default constructor is usually publicusually public..

default constructordefault constructor

Page 22: Objects and Classes Writing Your Own Classes A review

The The DiceDice Class Class

The The default constructor default constructor is called automatically when the is called automatically when the program loadsprogram loads

when a dice object is instantiated with a statement such as:when a dice object is instantiated with a statement such as:

Dice dice = new Dice();Dice dice = new Dice(); oror

Dice dice;Dice dice;dice = new Dice();dice = new Dice();

Page 23: Objects and Classes Writing Your Own Classes A review

The The default constructor default constructor is called automatically when the program is called automatically when the program loadsloads

when a dice object is instantiated with a statement such as:when a dice object is instantiated with a statement such as:

Dice dice = new Dice();Dice dice = new Dice(); oror

Dice dice;Dice dice;dice = new Dice();dice = new Dice();

oror

If no constructor is coded, java provides a default If no constructor is coded, java provides a default constructor with no parametersconstructor with no parameters

The The DiceDice Class Class

Page 24: Objects and Classes Writing Your Own Classes A review

In other words, the default constructorIn other words, the default constructor instantiates a Dice object instantiates a Dice object

Another name for the default constructor is the Another name for the default constructor is the no-argument constructor.no-argument constructor.

A program cannot call the default constructor directly;A program cannot call the default constructor directly;

it is invoked via the it is invoked via the new operatornew operator when you create an object when you create an object of the class e.g.of the class e.g.

Dice d = Dice d = new new Dice();Dice();

default constructordefault constructor

Page 25: Objects and Classes Writing Your Own Classes A review

public Dice(int n) public Dice(int n) // the one-argument constructor// the one-argument constructor{{ numDice = n;numDice = n;}}

This code is the This code is the one-argument constructorone-argument constructor. .

The one argument constructor creates a Dice object and The one argument constructor creates a Dice object and initializes initializes the instance variable numDicethe instance variable numDice

There is There is no limit to the number of constructorsno limit to the number of constructors that you can include that you can include in a class definition.in a class definition.

A A DiceDice Class - a default constructor Class - a default constructor

Page 26: Objects and Classes Writing Your Own Classes A review

A A two-argument constructortwo-argument constructor might have the form: might have the form:

public Dice( int numBlueDice, int numRedDice)public Dice( int numBlueDice, int numRedDice)

{{

numDice = numBlueDice + numRedDice;numDice = numBlueDice + numRedDice;

}}

If a class defines no constructors at all, If a class defines no constructors at all,

Java provides a Java provides a default constructor default constructor that creates and instantiates that creates and instantiates objects. objects.

A A DiceDice Class Class

Page 27: Objects and Classes Writing Your Own Classes A review

Lines 16-24: rollDiceLines 16-24: rollDice::

The method The method rollDice() simulates rolling the set ofrollDice() simulates rolling the set of dice dice according to the following algorithm:according to the following algorithm:

1.1. Declare a local variable sum.Declare a local variable sum.

2.2. Instantiate a Random object, Instantiate a Random object, random.random.

3.3. For each die in the set, i.e.For each die in the set, i.e.

4.4. for for ii = 1 to numDice, = 1 to numDice,5.5.

a. a. generate a random number generate a random number between 1 and 6, inclusive, andbetween 1 and 6, inclusive, and6.6.

b. add the random number to sum.b. add the random number to sum.

7.7. return sum.return sum.

Page 28: Objects and Classes Writing Your Own Classes A review

The method rollDice() has public access The method rollDice() has public access

which specifies that the method is visible which specifies that the method is visible

and accessible outside the Dice class.and accessible outside the Dice class.

PUBLIC ACCESSPUBLIC ACCESS

Page 29: Objects and Classes Writing Your Own Classes A review

Lines 23-30: Lines 23-30: Getter methods return variable valuesGetter methods return variable values

The public method The public method getNumDice() returns the value of numDicegetNumDice() returns the value of numDice..

A method such as A method such as getNumDice() that returns the value of some getNumDice() that returns the value of some private variable is called a private variable is called a gettergetter method method..

A A DiceDice Class Class

Page 30: Objects and Classes Writing Your Own Classes A review

Lines 29-32:Lines 29-32:

public method public method setNumDice(int n)setNumDice(int n) provides access to NumDiceprovides access to NumDice

It sets It sets numDicnumDicee to the value of to the value of parameter parameter n. n.

A method that assigns or alters the value of an instance variable A method that assigns or alters the value of an instance variable is called a is called a settersetter method. method.

A Dice ClassA Dice Class

Page 31: Objects and Classes Writing Your Own Classes A review

A Test Class for DiceA Test Class for Dice1.1.public class TestDicepublic class TestDice2.2.{{3.3. public static void main(String[] args) public static void main(String[] args) // for testing the Dice class// for testing the Dice class4.4. {{5.5. Dice d1 = new Dice(); Dice d1 = new Dice(); // Declare two dice objects// Declare two dice objects6.6. Dice d2 = new Dice(2);Dice d2 = new Dice(2);7.7. 8.8.// CALL GETTER METHODS FOR NUMBER OF DICE// CALL GETTER METHODS FOR NUMBER OF DICE9.9. System.out.println( “d1: numDice = “ + d1.getNumDice());System.out.println( “d1: numDice = “ + d1.getNumDice());10.10. System.out.println( “d2: numDice = “ + d2.getNumDice());System.out.println( “d2: numDice = “ + d2.getNumDice());

11.11. // ROLL DICE 10 TIMES// ROLL DICE 10 TIMES12.12. for (int i = 1; i <= 10; i++)for (int i = 1; i <= 10; i++)13.13. System.out.println(d1.rollDice() + “ “+ d2.rollDice());System.out.println(d1.rollDice() + “ “+ d2.rollDice());

14.14.// SET NUMBER OF DICE TO 5 For d1// SET NUMBER OF DICE TO 5 For d115.15. d1.setNumDice(5);d1.setNumDice(5);16.16. System.out.println( “d1: numDice = “ + d1.getNumDice());System.out.println( “d1: numDice = “ + d1.getNumDice());17.17. for (int i = 1; i <= 10; i++)for (int i = 1; i <= 10; i++)18.18. System.out.println(d1.rollDice() );System.out.println(d1.rollDice() );19.19. }}20.20.}}

Page 32: Objects and Classes Writing Your Own Classes A review

Each class that we write has the following structure:Each class that we write has the following structure:

[access modifier [access modifier –” public or private” –” public or private” ] ] class nameclass name

{{

* * instanceinstance variables or fieldsvariables or fields

* constructors* constructors

* methods* methods

}}

A More General Look At ClassesA More General Look At Classes

Page 33: Objects and Classes Writing Your Own Classes A review

A More General Look At ClassesA More General Look At Classes

Page 34: Objects and Classes Writing Your Own Classes A review

A class’s access modifier is optional. A class’s access modifier is optional.

For now, we designate each of our classes as publicFor now, we designate each of our classes as public..

Java specifies that only Java specifies that only one public class can be saved in one public class can be saved in any fileany file,,

so each class must be saved in a separate file. so each class must be saved in a separate file.

The name of the file must be The name of the file must be “classname.java”. “classname.java”.

For example, the Dice class is a public class and must be For example, the Dice class is a public class and must be saved as saved as Dice.java.Dice.java.

Page 35: Objects and Classes Writing Your Own Classes A review

Java convention dictates that Java convention dictates that each class name begins each class name begins with an uppercase letter. with an uppercase letter.

All other letters of a class name are lowercaseAll other letters of a class name are lowercase except except those that begin new “words.” those that begin new “words.”

Some other permissible and reasonable names for the Some other permissible and reasonable names for the Dice class are: Dice class are: MyDice, MyLoadedDiceMyDice, MyLoadedDice

A More General Look At ClassesA More General Look At Classes

Page 36: Objects and Classes Writing Your Own Classes A review

A class can have any number of A class can have any number of instance variablesinstance variables or or fieldsfields. .

Each field has an optional Each field has an optional access modifier:access modifier:

public – The field is visible outside the class.public – The field is visible outside the class. private – The field is visible only to the methods of the class.private – The field is visible only to the methods of the class.

Normally, we specify Normally, we specify instance variableinstance variables as s as private. private.

Private instance variablesPrivate instance variables are accessible only through the are accessible only through the methods of the class.methods of the class. Usually, a Usually, a class’s methods regulate all access to the instance class’s methods regulate all access to the instance variables.variables.

The Dice class has just one instance variable, numDice, which is The Dice class has just one instance variable, numDice, which is private. private.

Page 37: Objects and Classes Writing Your Own Classes A review

Each class has at least one constructor. Each class has at least one constructor.

A constructor is automatically executed each time an object of the class is instantiated. A constructor is automatically executed each time an object of the class is instantiated.

A constructor initializes instance variables but it can also perform other computations. A constructor initializes instance variables but it can also perform other computations.

The name of a constructor is the same as the class name. The name of a constructor is the same as the class name.

A constructor does not have a return value. A constructor does not have a return value.

The The default constructor default constructor ((no-argument constructorno-argument constructor) is a constructor with no ) is a constructor with no parameters. parameters.

The Dice class has two constructors:The Dice class has two constructors:

the default constructor: public Dice()the default constructor: public Dice() one-argument constructor: one-argument constructor: public Dice(int n)public Dice(int n)

Constructor ReviewConstructor Review

Page 38: Objects and Classes Writing Your Own Classes A review

Rules for constructorsRules for constructors

If a class If a class does not implement a constructor, does not implement a constructor,

Java provides a Java provides a default, no-argument constructor. default, no-argument constructor.

Page 39: Objects and Classes Writing Your Own Classes A review

An application can create an object with Java's default constructor An application can create an object with Java's default constructor using a statement such as:using a statement such as:

MyClass myClass = new MyClass() MyClass myClass = new MyClass() // default constructor // default constructor provided by Java provided by Java

ConstructorsConstructors

Page 40: Objects and Classes Writing Your Own Classes A review

The methods of the class specify the behaviors of the class. The methods of the class specify the behaviors of the class.

Each method has an Each method has an optional access modifier optional access modifier

public or private.public or private.

A private method is intended for use only within its classA private method is intended for use only within its class. .

Methods ReviewMethods Review

Page 41: Objects and Classes Writing Your Own Classes A review

In addition to instance variables, In addition to instance variables,

a Java class may also define a Java class may also define class variables class variables or staticor static variables. variables.

Also called a class variable. Also called a class variable.

A A static variablestatic variable belongs to the class and not to any particular belongs to the class and not to any particular object;object;

a class or static variable is shared by all objects of the class. a class or static variable is shared by all objects of the class.

StaticStatic Data or Class Variables Data or Class Variables

Page 42: Objects and Classes Writing Your Own Classes A review

Once defined in a class, Once defined in a class,

a a static variable exists whether or not any objects have been static variable exists whether or not any objects have been created; created;

and no matter how many objects exist, and no matter how many objects exist,

only one copy of any static variable can exist. only one copy of any static variable can exist.

static variablesstatic variables

Page 43: Objects and Classes Writing Your Own Classes A review

Static data is not stored in an individual objectStatic data is not stored in an individual object

but in a separate location, but in a separate location,

and all objects of a class have access to this one location. and all objects of a class have access to this one location.

Static VariablesStatic Variables

Page 44: Objects and Classes Writing Your Own Classes A review

An Employee class models an individual employee and An Employee class models an individual employee and

that each employee has a that each employee has a unique weekly income. unique weekly income.

A static variable A static variable totalPayrolltotalPayroll might hold the grand total of all might hold the grand total of all salaries for the week. salaries for the week.

Only one copy of totalPayroll is necessary. Only one copy of totalPayroll is necessary.

All objects All objects share totalPayrollshare totalPayroll. .

Static VariablesStatic Variables

Page 45: Objects and Classes Writing Your Own Classes A review

All Employee objects share the same All Employee objects share the same staticstatic variable, variable, totalPayrolltotalPayroll

StaticStatic Data or Class Variables Data or Class Variables

Page 46: Objects and Classes Writing Your Own Classes A review

1.1. import java.util.*;import java.util.*;

2.2. public class Dicepublic class Dice

3.3. {{

4.4. private int numDice;private int numDice;

5.5. private Random random;private Random random;

6.6. // the keyword // the keyword staticstatic denotes a class variable denotes a class variable ..  

7.7. static private int numDiceObjects = 0static private int numDiceObjects = 0; // shared by all classes; // shared by all classes

8.8. public Dice() public Dice() // default constructor -- one die // default constructor -- one die

9.9. {{

10.10. numDice = 1;numDice = 1;

11.11. random = new Random();random = new Random();

12.12. numDiceObjects++; numDiceObjects++; // incremented every time a Dice is created// incremented every time a Dice is created13.13. }}   

14.14.

15.15. public Dice(int n) public Dice(int n) // one argument constructor --n dice// one argument constructor --n dice

16.16. { {

17.17. numDice = n;numDice = n;

18.18. random = new Random();random = new Random();

19.19. numDiceObjects++;numDiceObjects++;

20.20. } } 

21.21.

Page 47: Objects and Classes Writing Your Own Classes A review

1.1. public int rollDice()public int rollDice()

2.2. // Returns the number of spots shown when tossing numDice dice// Returns the number of spots shown when tossing numDice dice3.3. {{4.4. int sum = 0;int sum = 0;

5.5. for (int i = 1; i <= numDice; ifor (int i = 1; i <= numDice; i++) // for each die in the set++) // for each die in the set6.6. sum += random.nextInt(6) + 1; sum += random.nextInt(6) + 1; // sum = an integer between 1 and 6, inclusi// sum = an integer between 1 and 6, inclusiveve7.7. return sum;return sum;8.8. } } 

9.9. public int getNumDice()public int getNumDice()10.10. {{11.11. return numDice;return numDice;12.12. } } 

13.13. public void setNumDice(int n)public void setNumDice(int n)14.14. {{15.15. numDice = n;numDice = n;16.16. }}

17.17. public int getNumDiceObjects()public int getNumDiceObjects()18.18. {{19.19. return numDiceObjects;return numDiceObjects;20.20. }}21.21. }}

Page 48: Objects and Classes Writing Your Own Classes A review

The constructors increment this static variable – The constructors increment this static variable –

keeping track of the number of Dice objects that have been created. keeping track of the number of Dice objects that have been created.

Every time a Every time a new Dice object is created, new Dice object is created,

the constructor the constructor increases numDiceObjects by one. increases numDiceObjects by one.

StaticStatic Data or Class Variables Data or Class Variables

Page 49: Objects and Classes Writing Your Own Classes A review

If variable If variable numDiceObjects numDiceObjects had been placed in the constructor, had been placed in the constructor, with no static modifierwith no static modifier

numDiceObjectsnumDiceObjects would be would be reset to 0 each reset to 0 each time a new object was time a new object was created. created.

The initialization on line 7 is performed just once, The initialization on line 7 is performed just once, and not every and not every time a new object is created. time a new object is created.

Static VariablesStatic Variables

Page 50: Objects and Classes Writing Your Own Classes A review

Lines 1-3 instantiate 3 Dice objects and the static variable Lines 1-3 instantiate 3 Dice objects and the static variable numDiceObjectsnumDiceObjects has the value 3. has the value 3.

1.1. Dice d1 = new Dice(3);Dice d1 = new Dice(3);

2.2. Dice d2 = new Dice(7);Dice d2 = new Dice(7);

3.3. Dice d3 = new Dice(5);Dice d3 = new Dice(5);

StaticStatic Data or Class Variables Data or Class Variables

Page 51: Objects and Classes Writing Your Own Classes A review

Each time a Dice constructor is invoked, numDiceObjects Each time a Dice constructor is invoked, numDiceObjects increases.increases.

Dice d1 = new Dice(3);Dice d1 = new Dice(3);StaticStatic variable variable numDiceObjectsnumDiceObjects has the value 1 has the value 1

Dice d2 = new Dice(7);Dice d2 = new Dice(7);StaticStatic variable variable numDiceObjectsnumDiceObjects has the value 2. has the value 2.

StaticStatic Data or Class Variables Data or Class Variables

Page 52: Objects and Classes Writing Your Own Classes A review

Dice d3 = new Dice(5);Dice d3 = new Dice(5);

StaticStatic variable variable numDiceObjectsnumDiceObjects has the value 3 has the value 3

StaticStatic Data or Class Variables Data or Class Variables

Page 53: Objects and Classes Writing Your Own Classes A review

Because the value of a constant is final and cannot be changed, it makes sense to store a constant just once Because the value of a constant is final and cannot be changed, it makes sense to store a constant just once instead of in each object of the class. instead of in each object of the class.

1.1. public class Circlepublic class Circle2.2. {{3.3. static private double totalArea = 0.0;static private double totalArea = 0.0; //class variable//class variable4.4. public final static double PI = 3.14159;public final static double PI = 3.14159; //class variable//class variable5.5. private double radius;private double radius;6.6. public Circle()public Circle() //default constructor//default constructor7.7. {{8.8. radius = 1;radius = 1;9.9. totalArea = totalArea + PI*radius*radius; totalArea = totalArea + PI*radius*radius; // adds to the class variable// adds to the class variable10.10. }}11.11. public Circle(double r)public Circle(double r) //one argument constructor//one argument constructor12.12. {{13.13. radius= r;radius= r;14.14. totalArea = totalArea totalArea = totalArea + PI*radius*radius+ PI*radius*radius; // adds to the class variable; // adds to the class variable15.15. }}16.16. // The Circle class presumably has other methods besides constructors, // The Circle class presumably has other methods besides constructors, 17.17. // perhaps area() and circumference(). // perhaps area() and circumference(). 18.18. }}

StaticStatic Data or Class Variables Data or Class Variables

Page 54: Objects and Classes Writing Your Own Classes A review

PIPI and and totalAreatotalArea are are staticstatic variables variables

All object share these variablesAll object share these variables

StaticStatic Data or Class Variables Data or Class Variables

Page 55: Objects and Classes Writing Your Own Classes A review

Since Since PI exists whether or not any Circle object exists, PI exists whether or not any Circle object exists,

To access to PI (or any other accessible static variable) use the class name To access to PI (or any other accessible static variable) use the class name instead of an object identifier:instead of an object identifier:

Circle.PICircle.PI

PI can also be accessed PI can also be accessed via any Circle via any Circle object:object:Uses an objectUses an object USES name of the classUSES name of the class

Circle circ = new Circle(3.5);Circle circ = new Circle(3.5); Circle c = new Circle(3.5);Circle c = new Circle(3.5);

Double x = Double x = circ.PI* 15;circ.PI* 15; double x = double x = Circle.PI* 1Circle.PI* 1

StaticStatic Data or Class Variables Data or Class Variables

Page 56: Objects and Classes Writing Your Own Classes A review

In general, if a class contains a static variable,In general, if a class contains a static variable,

all objects/instances of the class all objects/instances of the class shareshare that variable; that variable;

the the variable belongs to the class variable belongs to the class and not to any particular and not to any particular object;object;

StaticStatic Data or Class Variables Data or Class Variables

Page 57: Objects and Classes Writing Your Own Classes A review

Static methods Static methods and and static variables static variables are are loaded into memory loaded into memory as as soon as the class is instantiatedsoon as the class is instantiated

Non-static or instance methods Non-static or instance methods require require an object an object to invoke them to invoke them

a static method may be called whether or not an object of the class a static method may be called whether or not an object of the class exists. exists.

StaticStatic Methods REVIEW Methods REVIEW

Page 58: Objects and Classes Writing Your Own Classes A review

static methodSstatic methodS The methodsThe methods

Math.random(), Math.sqrt(), and Math.abs() Math.random(), Math.sqrt(), and Math.abs() are all static methods. are all static methods.

Every method of Java’s Math class is static. Every method of Java’s Math class is static.

A A static method static method may be invoked by sending a message to an object, may be invoked by sending a message to an object, if one exists, or by using the class name. e.g.if one exists, or by using the class name. e.g.

Dice.getNumberofDice() ( Class Dice)Dice.getNumberofDice() ( Class Dice)

where the method where the method getNumberofDice()getNumberofDice() is declared static is declared static

Page 59: Objects and Classes Writing Your Own Classes A review

Example:Example:

  

1.1. public class Circlepublic class Circle

2.2. {{

3.3. staticstatic private double totalArea = 0.0; private double totalArea = 0.0; //static (class) variable//static (class) variable

4.4. public final public final staticstatic double PI = 3.14159; double PI = 3.14159; //static variable//static variable

5.5. private double radius;private double radius; // instance variable// instance variable

6.6.   

7.7. public Circle()public Circle() //default constructor//default constructor

8.8. {{

9.9. radius = 1;radius = 1;

10.10. totalArea += PI*radius*radius; // adds to the class variabletotalArea += PI*radius*radius; // adds to the class variable

11.11. }}

12.12.   

13.13. public Circle(double r)public Circle(double r) //one argument constructo//one argument constructorr

14.14. {{

15.15. radius= r;radius= r;

16.16. totalArea += PI*radius*radius; // adds to the class vriabletotalArea += PI*radius*radius; // adds to the class vriable

17.17. }}

18.18.   

19.19. public static double getTotalArea() public static double getTotalArea() // static method has access to static variable totalArea// static method has access to static variable totalArea

20.20. {{

21.21. return totalArea;return totalArea;

22.22. }}

23.23. // Other methods ……………………….// Other methods ……………………….

24.24. }}

25.25. To invoke the static method getTotalArea(), no objects need exist. If no objects To invoke the static method getTotalArea(), no objects need exist. If no objects

exist, the method call exist, the method call Circle.getTotalArea() Circle.getTotalArea() returns returns 0.0, 0.0, the the value value initially assigned to totalAreainitially assigned to totalArea..

Page 60: Objects and Classes Writing Your Own Classes A review

The one argument constructor of the Dice class:The one argument constructor of the Dice class:

public Dice(int n) public Dice(int n) { { numDice = n;numDice = n;

random = new Random();random = new Random(); }}

The statenment:The statenment:

numDice = n;numDice = n;  

assigns assigns nn to the instance variable numDice to the instance variable numDice..

The keyword The keyword thisthis

Page 61: Objects and Classes Writing Your Own Classes A review

public Dice(int n) public Dice(int n) { { numDice = n;numDice = n;

random = new Random();random = new Random(); }}

The The parameter name parameter name can also be called can also be called numDice, numDice,

the same name as the instance variablethe same name as the instance variable..

If the parameter is also named If the parameter is also named numDicenumDice, the constructor has the form:, the constructor has the form:

public Dice(int numDice) public Dice(int numDice) { { numDice = numDicenumDice = numDice; //which numDice????; //which numDice????

random = new Random();random = new Random(); }}  

The keyword The keyword thisthis

Page 62: Objects and Classes Writing Your Own Classes A review

The compiler The compiler always always assumesassumes that numDice in the statement that numDice in the statement

numDice = numDice;numDice = numDice;

refersrefers to the to the local variable, i.e., the parameter. local variable, i.e., the parameter.

So So numDice is assigned its own valuenumDice is assigned its own value, and , and

the the instance variable instance variable numDice is not assigned numDice is not assigned anyany value. value.

The keyword The keyword thisthis

Page 63: Objects and Classes Writing Your Own Classes A review

To distinguish between :To distinguish between :

the the instance variable and the parametinstance variable and the parameterer, Java provides the , Java provides the reference reference this.this.

The reference The reference this this refers to the refers to the current instance of a current instance of a class,class,

the object currently being used. the object currently being used.

THIS used in programsTHIS used in programs

Page 64: Objects and Classes Writing Your Own Classes A review

By using thisBy using this,, an object can refer to itself an object can refer to itself

public Dice( int numDice)public Dice( int numDice)

{{

thisthis.numDice = numDice; // .numDice = numDice; // this refers to instance this refers to instance variablevariable

random = new Random();random = new Random();

}}

thisthis.numDice refers to the instance variable .numDice refers to the instance variable numDicenumDice, ,

which which belongs to belongs to “this class,” , “this class,” ,

and and NOT NOT the parameter numDice.the parameter numDice.

The keyword The keyword thisthis

Page 65: Objects and Classes Writing Your Own Classes A review

The Rectangle class uses The Rectangle class uses thisthis in both the two-argument constructor and the method biggerRectangle(). in both the two-argument constructor and the method biggerRectangle().

  

1.1. public class Rectanglepublic class Rectangle

2.2. {{3.3. private int length, width;private int length, width;

4.4. public Rectangle (int length, int width)public Rectangle (int length, int width)5.5. {{

6.6. this.length = length this.length = length // this.length – is the instance variable length // this.length – is the instance variable length

7.7. this.width = widththis.width = width; // this.width – is the instance variable width; // this.width – is the instance variable width

8.8. }}9.9.

public public Rectangle Rectangle biggerRectangle (Rectangle biggerRectangle (Rectangle r)/r)// / returns the rectangle with larger areareturns the rectangle with larger area1.1. {{

2.2. if ( this.area() > r.area())if ( this.area() > r.area()) // // this.area() returns the area of the current (calling) objectthis.area() returns the area of the current (calling) object

3.3. // r.area() returns the area of the parameter object// r.area() returns the area of the parameter object

4.4. return thisreturn this; ; // return a reference to "this object" -- the calling object// return a reference to "this object" -- the calling object

5.5. elseelse6.6. return r;return r;7.7. }}8.8.

Using Using thisthis With a Method Call With a Method Call

Page 66: Objects and Classes Writing Your Own Classes A review

The following segment incrementally builds the string “Happy”:The following segment incrementally builds the string “Happy”:

1.1. String s = new String(“H”); String s = new String(“H”); // s // s “H” “H”

2.2. s += “a”; s += “a”; // s // s ”Ha” ”Ha”

3.3. s += “p”;s += “p”; // s // s “Hap” “Hap”

4.4. s += “p”; s += “p”; // s // s “Happ” “Happ”

5.5. s += “y’; s += “y’; // s // s “Happy” “Happy”

String objects are immutable and each concatenation operation causes the instantiation String objects are immutable and each concatenation operation causes the instantiation of a new String object. of a new String object.

Thus, the above segment creates five different String objects. Thus, the above segment creates five different String objects.

Each time a new object is created, its address is assigned to the reference variable s. Each time a new object is created, its address is assigned to the reference variable s.

After line 5 executes, there are four After line 5 executes, there are four unreferencedunreferenced String objects in existence. String objects in existence.

Garbage CollectionGarbage Collection

Page 67: Objects and Classes Writing Your Own Classes A review

  

With the creation of each new String object, previously created objects are no With the creation of each new String object, previously created objects are no longer accessiblelonger accessible

Garbage CollectionGarbage Collection

Page 68: Objects and Classes Writing Your Own Classes A review

The Java Virtual Machine automatically reclaims all memory The Java Virtual Machine automatically reclaims all memory allocated to unreferenced objects for future use. allocated to unreferenced objects for future use.

If an object is no longer referenced and accessible, the memory If an object is no longer referenced and accessible, the memory allocated to that object is freed and made available for the allocated to that object is freed and made available for the creation of other objects. creation of other objects.

This clean-up process is called This clean-up process is called garbage collectiongarbage collection. .

Garbage CollectionGarbage Collection

Page 69: Objects and Classes Writing Your Own Classes A review

Java’s Java’s garbage collectiongarbage collection is more like recycling. is more like recycling.

Java’s garbage collector periodically determines which objects Java’s garbage collector periodically determines which objects are unreferenced and reclaims the space allocated to those are unreferenced and reclaims the space allocated to those objects. objects.

As a program runs, garbage collection occurs transparently in As a program runs, garbage collection occurs transparently in the background.the background.

Garbage CollectionGarbage Collection

Page 70: Objects and Classes Writing Your Own Classes A review

If an object remains referenced but is no longer used in a program, the garbage collector does If an object remains referenced but is no longer used in a program, the garbage collector does notnot recycle the recycle the memory:memory:

Square mySquare = new Square (5.0); Square mySquare = new Square (5.0); // a 5.0 x 5.0 square// a 5.0 x 5.0 squaredouble areaSquare = mySquare.area();double areaSquare = mySquare.area();

Triangle myTriangle = new Triangle(6.0, 8.0);Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0// right triangle base = 6.0, height = 8.0double areaTriangle = myTriangle.area();double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); Circle myCircle = new Circle(4.0); // a circle of radius 4.0// a circle of radius 4.0double areaCircle = myCirclearea();double areaCircle = myCirclearea();……// code that uses these objects// code that uses these objects……// more code that does // more code that does not not use the objects created aboveuse the objects created above

......

When Square, Triangle and Circle objects are no longer used by the program, if the objects remain referenced, When Square, Triangle and Circle objects are no longer used by the program, if the objects remain referenced, that is, if references mySquare, myTrianglethat is, if references mySquare, myTriangle,, and and myCircle continue to hold the addresses of these obsolete myCircle continue to hold the addresses of these obsolete objects, the garbage collector will not reclaim the memory for these three objects. objects, the garbage collector will not reclaim the memory for these three objects.

Such a scenario causes a Such a scenario causes a memory leakmemory leak..

Garbage CollectionGarbage Collection

Page 71: Objects and Classes Writing Your Own Classes A review

A memory leak occurs when an application fails to release or recycle memory that is no longer needed. A memory leak occurs when an application fails to release or recycle memory that is no longer needed.

The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a few lines of The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a few lines of code (lines 9-11):code (lines 9-11):

Square mySquare = new Square (5.0); Square mySquare = new Square (5.0); // a 5.0 x 5.0 square// a 5.0 x 5.0 squaredouble areaSquare = mySquare.area();double areaSquare = mySquare.area();  Triangle myTriangle = new Triangle(6.0, 8.0);Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, // right triangle base = 6.0,

height = 8.0height = 8.0double areaTriangle = myTriangle.area();double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); Circle myCircle = new Circle(4.0); // a circle of radius 4.0// a circle of radius 4.0double areaCircle = myCircle.area()double areaCircle = myCircle.area()  // code that uses these objects// code that uses these objects……mySquare = null; mySquare = null; myTriangle = null;myTriangle = null;myCircle = null;myCircle = null;  // more code that does // more code that does notnot use the objects created use the objects created aboveabove

......

   The Java constant The Java constant nullnull can be assigned to a reference. can be assigned to a reference.

A reference with value null refers to no object and holds no address; it is called a A reference with value null refers to no object and holds no address; it is called a void referencevoid reference..

Garbage CollectionGarbage Collection

Page 72: Objects and Classes Writing Your Own Classes A review

Referenced and unreferenced objectsReferenced and unreferenced objects

Garbage CollectionGarbage Collection