Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects and Classes Writing Your Own Classes A review.

Similar presentations


Presentation on theme: "Objects and Classes Writing Your Own Classes A review."— Presentation transcript:

1 Objects and Classes Writing Your Own Classes A review

2 An object is an abstraction of some entity such as :  a car, a dog, a flea, a house, or a string of characters.  An object may be physical, like a radio,  or intangible, like a song. What is an object? What is an object?

3 Just as a noun is a Just as a noun is a person, place, or thing; person, place, or thing;  so is an object -  it is mostly a real word entity What is an object

4 I.E. Attributes(data) and behaviors (methods).  How is an object is instantiated ?.  Consider the class Dice An Object has methods & Data

5 A Dice class contains  the attributes (instance variables)  and the behaviors (Methods)  Of a collection of n six-sided dice.  Each Dice object has a single attribute:  an integer ( equal to the number of dice in the collection). 

6 The behaviors( methods ) consist of: A.“rolling the dice” - a method B. returns the total number of spots displayed on the faces of all the dice, AND C. returns the number of dice in the collection, AND D. changes the number of dice in the collection.

7 A Dice object is an abstraction of a set of n dice A Dice Class

8  The Dice class has methods that are available to other classes: e.g // Create a new Dice object // Create a new Dice object Dice d = new Dice(); Dice d = new Dice(); // call a method from the Dice class to roll the dice // call a method from the Dice class to roll the dice int value = d.rollDice(); int value = d.rollDice(); A Dice Class

9 Problem Statement: Design a Dice class that models a collection of  n six-sided dice. The class should provide three methods:  int rollDice(), which simulates tossing the dice and returns the total number of spots displayed on the dice,  int getNumDice(), which returns the number of dice in the set; and  void setNumDice(int n), which sets or changes the number of dice. A Dice Class

10 1. import java.util.*; // for the Random class 1. import java.util.*; // for the Random class 2. public class Dice 3. { 4. private int numDice; // Instance variables 5. private Random random; 6. 6. 7. public Dice() //default constructor -- one die in the set 8. { // default constructor has no parameters 9. numDice = 1; 10. random = new Random(); // set up random number generator 11. } 12. 12. 13. public Dice(int n) // one argument constructor -- n dice in the set 14. { 15. numDice = n; // sets the number of dice to “n” 16. random = new Random(); 17. }

11 public int rollDice( ) // Returns the number of spots shown when tossing numDice dice // Returns the number of spots shown when tossing numDice dice { 17. int sum = 0; 18. for (int i = 1; i <= numDice; i++) // for each die in the set 19. sum += random.nextInt(6) + 1; // sum = an integer // between 1 and 6, inclusive 20. return sum; 21. } 22. // setters amd getters methods return values of instance //variables 23. public int getNumDice() 24. { 25. return numDice; 26. } 27. public void setNumDice(int n) 28. { 29. numDice = n; 30. } 31. }

12  As you declare a String reference: String s = new String();  you can also declare a Dice reference Dice d = new Dice(); A Dice Class

13  Dice contains no main(...) method.  Like the String class,  Dice cannot run independently.  So you use the Dice class to create a game that uses dice. What to do with Dice?

14 Discussion: Dice must be saved in a file named Dice.java. (public class Dice) spelled as you declared it. (public class Dice) spelled as you declared it.  Java convention dictates that the name of a class begins with an uppercase letter.  All other letters are lowercase, except those that begin new words. A Dice Class

15  The word public is an access modifier.  If a class is specified as public  then the class can be used by any other class.  Only one public class can be saved in any file. Class Naming

16 Line 4: private int numDice  The integer variable numDice is an instance variable or field  numDice is visible to all methods of the class.  Any method defined in Dice therefore can use this variable. A Dice Class - what code does

17 Organization of the class

18  numDice is specified as private,  Therefore: only the methods of Dice can access or modify numDice.  The field numDice is not visible outside the Dice class.  Instance variables usually are given private access so outside classes cannot access them directly PRIVATE ACCESS

19  public access specifies that the variable is accessible to all code outside the class  and a variable with no access modifier is accessible to classes within its package. However, we will look at another modifier later.  Private access dictates that the variable is not visible outside the class. Public access allows all classes in

20 Lines 6-10: public Dice() // the default constructor -- one die public Dice() // the default constructor -- one die { numDice = 1; numDice = 1; }  The code on lines 6-10 is the class’s default constructor.  The default constructor is like a method but there is no return value, not even void. A Dice Class

21  The name of the default constructor is the same as the class name.  The default constructor creates or instantiates a new object of the Dice class,  that is, the default constructor allocates memory for each object of a class.  The access modifier for the default constructor is usually public. default constructor

22 The Dice Class  The default constructor is called automatically when the program loads  when a dice object is instantiated with a statement such as: Dice dice = new Dice(); or or Dice dice; dice = new Dice();

23  The default constructor is called automatically when the program loads  when a dice object is instantiated with a statement such as: Dice dice = new Dice(); or or Dice dice; dice = new Dice(); or or If no constructor is coded, java provides a default constructor with no parameters If no constructor is coded, java provides a default constructor with no parameters The Dice Class

24  In other words, the default constructor  instantiates a Dice object  Another name for the default constructor is the no-argument constructor.  A program cannot call the default constructor directly;  it is invoked via the new operator when you create an object of the class e.g.  Dice d = new Dice(); default constructor

25 public Dice(int n) // the one-argument constructor { numDice = n; numDice = n;}  This code is the one-argument constructor.  The one argument constructor creates a Dice object and initializes the instance variable numDice  There is no limit to the number of constructors that you can include in a class definition. A Dice Class - a default constructor

26  A two-argument constructor might have the form: public Dice( int numBlueDice, int numRedDice) { numDice = numBlueDice + numRedDice; }  If a class defines no constructors at all,  Java provides a default constructor that creates and instantiates objects. A Dice Class

27 Lines 16-24: rollDice :  The method rollDice() simulates rolling the set of dice according to the following algorithm: 1. Declare a local variable sum. 2. Instantiate a Random object, random. 3. For each die in the set, i.e. 4. for i = 1 to numDice, 5. a. generate a random number between 1 and 6, inclusive, and 6. b. add the random number to sum. 7. return sum.

28  The method rollDice() has public access  which specifies that the method is visible  and accessible outside the Dice class. PUBLIC ACCESS

29 Lines 23-30: Getter methods return variable values  The public method getNumDice() returns the value of numDice.  A method such as getNumDice() that returns the value of some private variable is called a getter method. A Dice Class

30 Lines 29-32:  public method setNumDice(int n) provides access to NumDice  It sets numDice to the value of parameter n.  A method that assigns or alters the value of an instance variable is called a setter method. A Dice Class

31 A Test Class for Dice 1. public class TestDice 2. { 3. public static void main(String[] args) // for testing the Dice class 4. { 5. Dice d1 = new Dice(); // Declare two dice objects 6. Dice d2 = new Dice(2); 7. 7. 8. // CALL GETTER METHODS FOR NUMBER OF DICE 9. System.out.println( “d1: numDice = “ + d1.getNumDice()); 10. System.out.println( “d2: numDice = “ + d2.getNumDice()); 11. // ROLL DICE 10 TIMES 12. for (int i = 1; i <= 10; i++) 13. System.out.println(d1.rollDice() + “ “+ d2.rollDice()); 14. // SET NUMBER OF DICE TO 5 For d1 15. d1.setNumDice(5); 16. System.out.println( “d1: numDice = “ + d1.getNumDice()); 17. for (int i = 1; i <= 10; i++) 18. System.out.println(d1.rollDice() ); 19. } 20. }

32 Each class that we write has the following structure: Each class that we write has the following structure: [access modifier –” public or private” ] class name { * instance variables or fields * instance variables or fields * constructors * constructors * methods } A More General Look At Classes

33

34  A class’s access modifier is optional.  For now, we designate each of our classes as public.  Java specifies that only one public class can be saved in any file,  so each class must be saved in a separate file.  The name of the file must be “classname.java”.  For example, the Dice class is a public class and must be saved as Dice.java.

35  Java convention dictates that each class name begins with an uppercase letter.  All other letters of a class name are lowercase except those that begin new “words.”  Some other permissible and reasonable names for the Dice class are: MyDice, MyLoadedDice A More General Look At Classes

36  A class can have any number of instance variables or fields.  Each field has an optional access modifier:  public – The field is visible outside the class.  private – The field is visible only to the methods of the class.  Normally, we specify instance variables as private.  Private instance variables are accessible only through the methods of the class.   Usually, a class’s methods regulate all access to the instance variables.  The Dice class has just one instance variable, numDice, which is private.

37  Each class has at least one constructor.  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.  The name of a constructor is the same as the class name.  A constructor does not have a return value.  The default constructor (no-argument constructor) is a constructor with no parameters.  The Dice class has two constructors:  the default constructor: public Dice()  one-argument constructor: public Dice(int n) Constructor Review

38  Rules for constructors  If a class does not implement a constructor, Java provides a default, no-argument constructor. Java provides a default, no-argument constructor.

39 An application can create an object with Java's default constructor using a statement such as:  MyClass myClass = new MyClass() // default constructor provided by Java Constructors

40  The methods of the class specify the behaviors of the class.  Each method has an optional access modifier  public or private. A private method is intended for use only within its class. A private method is intended for use only within its class. Methods Review

41  In addition to instance variables,  a Java class may also define class variables or static variables.  Also called a class variable.  A static variable belongs to the class and not to any particular object;  a class or static variable is shared by all objects of the class. Static Data or Class Variables

42  Once defined in a class,  a static variable exists whether or not any objects have been created;  and no matter how many objects exist,  only one copy of any static variable can exist. static variables

43  Static data is not stored in an individual object  but in a separate location,  and all objects of a class have access to this one location. Static Variables

44  An Employee class models an individual employee and  that each employee has a unique weekly income.  A static variable totalPayroll might hold the grand total of all salaries for the week.  Only one copy of totalPayroll is necessary.  All objects share totalPayroll. Static Variables

45 All Employee objects share the same static variable, totalPayroll All Employee objects share the same static variable, totalPayroll Static Data or Class Variables

46 1. import java.util.*; 2. public class Dice 3. { 4. private int numDice; 5. private Random random; 6. // the keyword static denotes a class variable. 6. // the keyword static denotes a class variable. 7. static private int numDiceObjects = 0; // shared by all classes 8. public Dice() // default constructor -- one die 9. { 10. numDice = 1; 11. random = new Random(); 12. numDiceObjects++; // incremented every time a Dice is created 13. } 13. } 14. 14. 15. public Dice(int n) // one argument constructor --n dice 16. { 17. numDice = n; 18. random = new Random(); 19. numDiceObjects++; 20. } 20. } 21. 21.

47 1. public int rollDice() 2. // Returns the number of spots shown when tossing numDice dice 3. { 4. int sum = 0; 5. for (int i = 1; i <= numDice; i++) // for each die in the set 6. sum += random.nextInt(6) + 1; // sum = an integer between 1 and 6, inclusive 7. return sum; 8. } 8. } 9. public int getNumDice() 10. { 11. return numDice; 12. } 12. } 13. public void setNumDice(int n) 14. { 15. numDice = n; 16. } 17. public int getNumDiceObjects() 18. { 19. return numDiceObjects; 20. } 21. }

48  The constructors increment this static variable –  keeping track of the number of Dice objects that have been created.  Every time a new Dice object is created,  the constructor increases numDiceObjects by one. Static Data or Class Variables

49  If variable numDiceObjects had been placed in the constructor, with no static modifier  numDiceObjects would be reset to 0 each time a new object was created.  The initialization on line 7 is performed just once, and not every time a new object is created. Static Variables

50  Lines 1-3 instantiate 3 Dice objects and the static variable numDiceObjects has the value 3. 1. Dice d1 = new Dice(3); 2. Dice d2 = new Dice(7); 3. Dice d3 = new Dice(5); Static Data or Class Variables

51  Each time a Dice constructor is invoked, numDiceObjects increases. Dice d1 = new Dice(3); Static variable numDiceObjects has the value 1 Dice d2 = new Dice(7); Static variable numDiceObjects has the value 2. Static Data or Class Variables

52 Dice d3 = new Dice(5); Static variable numDiceObjects has the value 3 Static Data or Class Variables

53  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. 1. public class Circle 2. { 3. static private double totalArea = 0.0;//class variable 4. public final static double PI = 3.14159;//class variable 5. private double radius; 6. public Circle()//default constructor 7. { 8. radius = 1; 9. totalArea = totalArea + PI*radius*radius; // adds to the class variable 10. } 11. public Circle(double r)//one argument constructor 12. { 13. radius= r; 14. totalArea = totalArea + PI*radius*radius; // adds to the class variable 15. } 16. // The Circle class presumably has other methods besides constructors, 17. // perhaps area() and circumference(). 18. } Static Data or Class Variables

54 PI and totalArea are static variables All object share these variables Static Data or Class Variables

55  Since PI exists whether or not any Circle object exists,  To access to PI (or any other accessible static variable) use the class name instead of an object identifier: Circle.PI  PI can also be accessed via any Circle object: Uses an objectUSES name of the class Circle circ = new Circle(3.5);Circle c = new Circle(3.5); Double x = circ.PI* 15;double x = Circle.PI* 1 Static Data or Class Variables

56  In general, if a class contains a static variable,  all objects/instances of the class share that variable;  the variable belongs to the class and not to any particular object; Static Data or Class Variables

57  Static methods and static variables are loaded into memory as soon as the class is instantiated   Non-static or instance methods require an object to invoke them  a static method may be called whether or not an object of the class exists. Static Methods REVIEW

58 static methodS  The methods  Math.random(), Math.sqrt(), and Math.abs() are all static methods.  Every method of Java’s Math class is static.  A static method may be invoked by sending a message to an object, if one exists, or by using the class name. e.g. Dice.getNumberofDice() ( Class Dice) Dice.getNumberofDice() ( Class Dice)  where the method getNumberofDice() is declared static

59 Example: 1. public class Circle 2. { 3. static private double totalArea = 0.0;//static (class) variable 4. public final static double PI = 3.14159;//static variable 5. private double radius;// instance variable 6. 6. 7. public Circle()//default constructor 8. { 9. radius = 1; 10. totalArea += PI*radius*radius; // adds to the class variable 11. } 12. 12. 13. public Circle(double r)//one argument constructor 14. { 15. radius= r; 16. totalArea += PI*radius*radius; // adds to the class vriable 17. } 18. 18. 19. public static double getTotalArea() // static method has access to static variable totalArea 20. { 21. return totalArea; 22. } 23. // Other methods ………………………. 24. }  To invoke the static method getTotalArea(), no objects need exist. If no objects exist, the method call Circle.getTotalArea() returns 0.0, the value initially assigned to totalArea.

60  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: numDice = n; assigns n to the instance variable numDice. The keyword this

61 public Dice(int n) { numDice = n; numDice = n; random = new Random(); random = new Random(); }  The parameter name can also be called numDice,  the same name as the instance variable.  If the parameter is also named numDice, the constructor has the form: public Dice(int numDice) public Dice(int numDice) { numDice = numDice ; //which numDice???? numDice = numDice ; //which numDice???? random = new Random(); } The keyword this

62  The compiler always assumes that numDice in the statement numDice = numDice; refers to the local variable, i.e., the parameter. refers to the local variable, i.e., the parameter.  So numDice is assigned its own value, and  the instance variable numDice is not assigned any value. The keyword this

63  To distinguish between :  the instance variable and the parameter, Java provides the reference this.  The reference this refers to the current instance of a class,  the object currently being used. THIS used in programs

64  By using this, an object can refer to itself public Dice( int numDice) { this.numDice = numDice; // this refers to instance variable this.numDice = numDice; // this refers to instance variable random = new Random(); random = new Random();} this.numDice refers to the instance variable numDice, this.numDice refers to the instance variable numDice, which belongs to “this class,”, which belongs to “this class,”, and NOT the parameter numDice. and NOT the parameter numDice. The keyword this

65  The Rectangle class uses this in both the two-argument constructor and the method biggerRectangle(). 1. public class Rectangle 2. { 3. private int length, width; 4. public Rectangle (int length, int width) 5. { 6. this.length = length // this.length – is the instance variable length 7. this.width = width; // this.width – is the instance variable width 8. } 9. 9. public Rectangle biggerRectangle (Rectangle r)// returns the rectangle with larger area public Rectangle biggerRectangle (Rectangle r)// returns the rectangle with larger area 1. { 2. if ( this.area() > r.area()) // this.area() returns the area of the current (calling) object 3. // r.area() returns the area of the parameter object 4. return this; // return a reference to "this object" -- the calling object 5. else 6. return r; 7. } 8. 8. Using this With a Method Call

66  The following segment incrementally builds the string “Happy”: 1. String s = new String(“H”); // s  “H” 2. s += “a”; // s  ”Ha” 3. s += “p”; // s  “Hap” 4. s += “p”; // s  “Happ” 5. s += “y’; // s  “Happy”  String objects are immutable and each concatenation operation causes the instantiation of a new String object.  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.  After line 5 executes, there are four unreferenced String objects in existence. Garbage Collection

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

68  The Java Virtual Machine automatically reclaims all memory allocated to unreferenced objects for future use.  If an object is no longer referenced and accessible, the memory allocated to that object is freed and made available for the creation of other objects.  This clean-up process is called garbage collection. Garbage Collection

69  Java’s garbage collection is more like recycling.  Java’s garbage collector periodically determines which objects are unreferenced and reclaims the space allocated to those objects.  As a program runs, garbage collection occurs transparently in the background. Garbage Collection

70  If an object remains referenced but is no longer used in a program, the garbage collector does not recycle the memory: Square mySquare = new Square (5.0); // a 5.0 x 5.0 square double areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0);// right triangle base = 6.0, height = 8.0 double areaTriangle = myTriangle.area(); Circle myCircle = new Circle(4.0); // a circle of radius 4.0 double areaCircle = myCirclearea(); … // code that uses these objects … // more code that does not use the objects created above...  When Square, Triangle and Circle objects are no longer used by the program, if the objects remain referenced, that is, if references mySquare, myTriangle, and myCircle continue to hold the addresses of these obsolete objects, the garbage collector will not reclaim the memory for these three objects.  Such a scenario causes a memory leak. Garbage Collection

71  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 code (lines 9-11): Square mySquare = new Square (5.0); // a 5.0 x 5.0 square double areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0);// right triangle base = 6.0, height = 8.0 double areaTriangle = myTriangle.area(); double areaTriangle = myTriangle.area(); Circle myCircle = new Circle(4.0); // a circle of radius 4.0 double areaCircle = myCircle.area() // code that uses these objects … mySquare = null; myTriangle = null; myCircle = null; // more code that does not use the objects created above...  The Java constant null can be assigned to a reference.  A reference with value null refers to no object and holds no address; it is called a void reference. Garbage Collection

72 Referenced and unreferenced objects Garbage Collection


Download ppt "Objects and Classes Writing Your Own Classes A review."

Similar presentations


Ads by Google