600 likes | 737 Views
More About Objects and Methods. Chapter 6. Objectives. Define and use constructors Write and use static variables and methods Use methods from class Math Use predefined wrapper classes Use stubs, drivers to test classes and programs Write and use overloaded methods
E N D
More About Objects and Methods Chapter 6
Objectives • Define and use constructors • Write and use static variables and methods • Use methods from class Math • Use predefined wrapper classes • Use stubs, drivers to test classes and programs • Write and use overloaded methods • Define and use enumeration methods • Define and use packages and import statements • Add buttons and icons to applets • Use event-driven programming in an applet
Constructors: Outline • Defining Constructors • Calling Methods from Constructors • Calling a Constructor from Other Constructors
Defining Constructors • A special method called when instance of an object created with new • Create objects • Initialize values of instance variables • Can have parameters • To specify initial values if desired • May have multiple definitions • Each with different numbers or types of parameters
Defining Constructors • Example class to represent pets • Figure 6.1 Class Diagram for Class Pet
Defining Constructors • listing 6.1class Pet • Note different constructors • Default • With 3 parameters • With String parameter • With double parameter • listing 6.2class PetDemo
Defining Constructors Sample screen output
Defining Constructors • Constructor without parameters is the default constructor • Java will define this automatically if the class designer does not define any constructors • If you do define a constructor, Java will not automatically define a default constructor • Usually default constructors not included in class diagram
Defining Constructors • Figure 6.2 A constructor returning a reference
Calling Methods from Other Constructors • Constructor can call other class methods • listing 6.3class Pet2 • Note method set • Keeps from repeating code
Calling Constructor from Other Constructors • From listing 6.3 we have the initial constructor and method set class Pet2 • In the other constructors use the this reference to call initial constructor • listing 6.4 class Pet3 • Note calls to initial constructor • when defining a constructor, you may use this as a name for another constructor in the same class; must be the first action taken by the constructor
Quiz 4 • Write a constructor for a Java class named Book. The Book class has instance variables for title (a String), author (a String), year (an int), and numberOfPages (an int). The constructor you write will have two parameters, a String for the author of a book and an int for numberOfPages. • Make sure you write your name and your section of 145 on your paper. • Solution online
Last Time • Encapsulation • data types are implemented as memory locations • Data of primitive typestored in the memory location assigned to the variable • Variable of class typecontains memory address of object named by the variable • unit testing • constructors
About mid-term • Check the past mid-term exam online, we’ll go over it next Monday • No quiz next Monday • If the dropbox doesn’t work, email your solutions to the TAs before deadline, or you won’t be able to get the credit • Submit a .zip file: (on the department computer) use mouse to right click on the folder 7 zip add to “foldername.zip”
Static Variables & Methods: Outline • Static Variables • Static Methods • Dividing the Task of a main Method into Subtasks • Adding a main Method to a class • The Math Class • Wrapper Classes
Static Variables • Static variables are shared by all objects of a class • Variables declared static final are considered constants – value cannot be changed • Variables declared static (without final) can be changed • Only one instance of the variable exists • It can be accessed by all instances of the class • e.g. private static inti = 2;
Static Variables • Static variables also called class variables • Contrast with instance variables • Do not confuse class variables with variables of a class type • Both static variables and instance variables are sometimes called fields or data members
Static variable vs. instance variable • Class Book • object: book1, book2 • Instance variables could have different value for the two objects, e.g. author, the authors of the two books could be different • Static variables only have one copy for the class, e.g. fund, fund for the whole class or all the objects of this class is the same • demo
Static variable vs. instance variable (static variables in Book) publisher fund INTEREST_RATE Methods in the class Book this author1 title1 year1 numberOfPages1 book1 this author2 title2 year2 numberOfPages2 book2 Memory
Static Methods • Some methods may have no relation to any type of object • Example • Compute max of two integers • Convert character from upper- to lower case • Static method declared in a class • Can be invoked without using an object • Instead use the class name
Tasks of main in Subtasks • Program may have • Complicated logic • Repetitive code • Create static methods to accomplish subtasks • demo
Adding Method main to a Class • Method main used so far in its own class within a separate file • Often useful to include method main within class definition • To create objects in other classes • To be run as a program (e.g. for testing) • demo
Last Time • static variables • static methods • Tips: write test codes in the same class, how to use static methods in main method
About assignments • Late homework not accepted. • If the dropbox doesn't work or anything goes wrong or • If Eclipse doesn’t work, type your code using a text editor, e.g., notepad, Microsoft word • Email your homework to the TAs BEFORE the deadline, or you'll get 0.
Old Test • http://www.cse.sc.edu/~huhns/csce145/Labs/lab12.html
The Math Class • Provides many standard mathematical methods • Automatically provided, no import needed • Example methods, figure 6.3a
The Math Class • Example methods, figure 6.3b
Random Numbers • Math.random()returns a random double that is greater than or equal to zero and less than 1 • Can scale using addition and multiplication; the following simulates rolling a six sided die int die = (int) (6.0 * Math.random()) + 1;
Wrapper Classes • Recall that arguments of primitive type treated differently from those of a class type • May need to treat primitive value as an object • Java provides wrapper classes for each primitive type • Methods provided to act on values • e.g. class Integer • Integer n = new Integer(42); //boxing • int i = n.intValue(); //unboxing
Wrapper Classes • The wrapper classes for the primitive types long, float, double, and char are Long, Float, Double, and Character, respectively. • The classes Long, Float, Double, and Character use the methods longValue, floatValue, doubleValue, and charValue, respectively • Integer n = new Integer(42); //boxing • Double d = new Double(9.99); • Character c = new Character('Z'); • Integer n2 = 42; // automatic boxing • int i = n.intValue(); //unboxing • int i2 = new Integer(42); // automatic unboxing
Wrapper Classes • The largest and smallest values of type int • Integer.MAX_VALUE • Integer.MIN_VALUE • in the class Integer: • public static final int MAX_VALUE = 2147483647; • Double of the wrapper class Double will convert a string to a value of type double. • Double.parseDouble("199.98") • Convert a value of type double to String • Double.toString(199.98) • Other wrapper classes have similar methods
Wrapper Classes • Allow programmer to have an object that corresponds to value of primitive type • Contain useful predefined constants and methods • Wrapper classes have no default constructor e.g.Integer n = new Integer(); // wrong! • Programmer must specify an initializing value when creating new object • Wrapper classes have no set methods
Wrapper Classes • Figure 6.4a Static methods in class Character
Wrapper Classes • Figure 6.4b Static methods in class Character
Writing Methods: Outline • Case Study: Formatting Output • Decomposition • Addressing Compiler Concerns • Testing Methods
Last Time • Old exam • Math class • Wrapper class First In-Class Exam Monday, October 7 • First Lab Exam Tuesday, October 8 • open book • Oct. 11, Fri. Last day to drop a course or withdraw without a grade of “WF” being recorded
Formatting Output Algorithm to display a double amount as dollars and cents: (pseudocode) 1. dollars = the number of whole dollars in amount. 2. cents = the number of cents in amount. Round if there are more than two digits after the decimal point. 3. Display a dollar sign, dollars, and a decimal point. 4. Display cents as a two-digit integer.
Formatting Output • listing 6.12class DollarFormatFirstTry • Note code to separate dollars and cents • Note if-else statement • listing 6.13class DollarFormatFirstTryDriver • Note call to the write method
Formatting Output Sample screen output
Formatting Output • listing 6.14class DollarFormat • Note code to handle negative values • Why are we using DollarFormat instead of double? want exact quantity (Java saves double and float as approximate quantity)
Decomposition • Recall pseudocode from previous slides • With this pseudocode we decomposethe task into subtasks • Then solve each subtask • Combine code of subtasks • Place in a method
Addressing Compiler Concerns • Compiler ensures necessary tasks are done • A method should contain no more than one return statement • believe the compiler
Null constant • String line = null; • null is a special defined constant (an address) that you can use to give a value to any variable of any class type, you can use == or != on it. • null is not an object; consider it as a place holder • use when necessary
Null Pointer Exception • Pet myDog = null; //no value for myDog yet • myDog.setPet(“Spot”, 2, 35.4); • //”Null Pointer Exception” error! • //null is not an object, can’t invoke methods • You should do • Pet myDog = new Pet(); • myDog.setPet(“Spot”, 2, 35.4);
Testing Methods • To test a method use a driver program • e.g. DollarFormatDriver.java • Every method in a class should be tested • Bottom-up testing • Test code at end of sequence of method calls first e.g. method A calls method B, you should test B first then A • Use a stub – simplified version of a method for testing purposes • e.g. put something simple such as printing sth. in method B, and then you can test A without testing B first
Overloading: Outline • Overloading Basics • Overloading and Automatic Type Conversion • Overloading and the Return Type • Programming Example: A Class for Money