University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Creating Your Own Class Lecture 7 Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump) Next Week: Review Ch 1-4 (that were previously assigned) (Reminder: Readings are absolutely vital for learning this stuff!) Some slides borrowed from Kurt Eiselt, Tamara Munzner, and Steve Wolfman. Some learning goals from Beth Simon. Labs and Tutorials This week is Lab #3. Lab #4 is up. Midterms Save the Dates! Midterm #1 is 5:30-6:30pm on February 10 (Tuesday) in Woodward IRC 2 Midterm #2 is 6-7pm on March 11 (Wednesday) in Woodward IRC 2 If you have a conflict with the first midterm, send me an email with your name, student ID number, and a brief explanation of your conflict, by noon, Tuesday, February 3! Extra Credit Survey Dr. Ben Yu is studying attitudes towards learning in introductory CS classes. Three surveys to complete during the term. Survey 1 is on WebCT now. Due January 28 These are completely optional. PeerWise Instructions For people participating in PeerWise, instructions are now available on WebCT. Your first questions/answers must be done by February 9. If you have questions/problems, please contact Paul Denny. However, to encourage participation, I will give 1 pt of extra credit, applied to your labs, if you complete all three surveys in time. 1
WebCT Bulletin Boards I encourage you to read and ask questions on the WebCT bulletin boards: Faster response time: many TAs, both profs, and fellow students read and respond. Everyone benefits from answer. Learning Center The TAs mentioned that they are in the CS Learning Center, ready to help, but often nobody shows up. Just a reminder that TAs are there, and they want to help you! Learning Goals By the end of the next several lectures you will be able to Create your own classes, with: Public and private fields and methods Helpful documentation that works with javadoc Basic principles i of abstraction and encapsulation (information hiding) Explain why abstraction and information hiding are important. Learning Goals By the end of class today you will be able to Create your own new class. Create simple methods in your class. Call your methods from another class. Trace the execution flow between the two classes. Pass parameters to your methods and return values. Declare instance variables in your class, make them private, and create getters/setters From Using to Creating Like the difference between buying clothes versus designing and sewing clothes: Buyer: Browses stores, looks for the clothes they want, gets the clothes, and wears them. Designer/Tailor: Tries to design clothing that people want, creates patterns for making the clothing, makes lots of clothes. (Designer/Tailor is also a buyer: buying fabric, thread, buttons, beading, etc. Using simpler objects to create new objects.) From Using to Creating Like the difference between buying clothes versus designing and sewing clothes: Using Classes: Browse Java library, look for the classes we want, import them, and use them. Creating Classes: Try to design classes that people want, create patterns for making objects, make objects. (Creator is also a user: we ll often use objects when creating new objects.) 2
Wait! We ve been doing this already! A Simple Java Program // Our first Java program. /* Traditionally, one s first program in a new language prints out Hello, World! */ public class HelloWorld { public static void main(string[ ] args) { System.out.println( Hello, World! ); A Simple Java Program // Our first Java program. /* Traditionally, one s first program in a new language prints out Hello, World! */ public class HelloWorld { public static void main(string[ ] args) { System.out.println( Hello, World! ); Last Few Lectures: Using classes import java.math.biginteger; BigInteger salary; salary = new BigInteger( 111222333 ); totalcompensation = salary.add(bonus); Using HelloWorld Using HelloWorld Not needed if.class file in same directory 3
Using HelloWorld Not needed if.class file in same directory HelloWorld foo; Using HelloWorld Not needed if.class file in same directory HelloWorld foo; foo = new HelloWorld(); Using HelloWorld Not needed if.class file in same directory HelloWorld foo; foo = new HelloWorld(); foo.main(null); // Don t worry about null Using HelloWorld Not needed if.class file in same directory HelloWorld foo; foo = new HelloWorld(); HelloWorld.main(null); // main is static Whoa what s going on? Sequential Execution Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. 4
Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. Bank Machine: Check PIN Check balance Dispense cash Dry Cleaner: Find clothes Deliver clothes Restaurant: Take order Prepare food Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. Bank Machine: Check PIN Check balance Dispense cash Dry Cleaner: Find clothes Deliver clothes Restaurant: Take order Prepare food Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. Bank Machine: Check PIN Check balance Dispense cash Dry Cleaner: Find clothes Deliver clothes Restaurant: Take order Prepare food Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. Bank Machine: Check PIN Check balance Dispense cash Dry Cleaner: Find clothes Deliver clothes Restaurant: Take order Prepare food Sequential Execution Suppose you have a list of tasks: Get money from bank machine. Pick up clothes from dry cleaner. Get lunch from takeout place. Bank Machine: Check PIN Check balance Dispense cash Dry Cleaner: Find clothes Deliver clothes Restaurant: Take order Prepare food Suppose you some Java statements: bonus = options.multiply(gain); p py(g ); total = salary.add(bonus); System.out.println(total); 5
Suppose you some Java statements: BigInteger Class: Suppose you some Java statements: BigInteger Class: bonus = options.multiply(gain); py(g total = salary.add(bonus); System.out.println(total); BigInteger multiply () { BigInteger add () { System Class: bonus = options.multiply(gain); py(g total = salary.add(bonus); System.out.println(total); BigInteger multiply () { BigInteger add () { System Class: Suppose you some Java statements: BigInteger Class: Suppose you some Java statements: BigInteger Class: bonus = options.multiply(gain); py(g total = salary.add(bonus); System.out.println(total); BigInteger multiply () { BigInteger add () { System Class: bonus = options.multiply(gain); py(g total = salary.add(bonus); System.out.println(total); BigInteger multiply () { BigInteger add () { System Class: How to Create a Class Suppose you some Java statements: BigInteger Class: Client Programmer: File MyClass.java bonus = options.multiply(gain); py(g total = salary.add(bonus); System.out.println(total); BigInteger multiply () { BigInteger add () { System Class: MyClass a; public class MyClass { 6
Client Programmer: How to Create a Class File MyClass.java Let s try it MyClass a; public class MyClass { a.sayhello(); public void sayhello() { System.out.println ( Hello ); Parameter Passing How do we get information into a method? We pass it parameters. ( pass as in passing the puck.) Creating New Methods Let s add a method for flattery: parameters Passing Parameters In the object user (the caller): a.flatter( fabulous ); In the class definition (the callee): Passing Parameters In the object user (the caller): a.flatter( fabulous ); In the class definition (the callee): 7
Review: Passing Parameters In the object user (the caller): a.flatter( fabulous ); adjective = fabulous In the class definition (the callee): Passing Parameters In the object user (the caller): a.flatter( fabulous ); adjective = fabulous In the class definition (the callee): Formal Parameters In the object user (the caller): a.flatter( fabulous ); In the class definition (the callee): The formal parameters define new variables. These are the types the method expects to get. Actual Parameters In the object user (the caller): a.flatter( fabulous ); In the class definition (the callee): The actual parameters are what gets passed when the method is called. Their values are copied into the formal parameters. Multiple Parameters? Let s add a method for flattery: formal parameters public void flatter(string interj, String adj) { System.out.println(interj + "You look " + adj + "!"); return Statement How do we get information back from the method? We use a return statement. ( return as in election returns results that come back to you) 8
return Statement The return statement in a method tells the method to return to the caller. Syntax: return; return expression; With an expression, it gets evaluated and that value is what the method call returns. Example Let s write a method that prints Hello on the screen and returns the number 42. (You ll use the return statement for much more interesting things later) Void Return Types Common confusion of output on screen versus returning a value. Can you say: int b = 3 + a.sayhello(); Void Return Types Common confusion of output on screen versus returning a value. Can you say: int b = 3 + a.sayhello(); No. sayhello returns type void. But we can use a method that has an int return type: int b = 3 + a.sayhelloandreturn42(); Questions? Objects Can Contain Variables It s convenient for objects to remember things about themselves, e.g.: java.awt.rectangle class in the book if we created a UBCStudent class To allow this, objects can have their own variables. Declare the variables in the class. But each (instance of an) object gets its own copy: Called instance fields or instance variables 9
Example Class: Celebrity public class Celebrity { String name; String description; Each Object Has Its Own Instance Fields You declare the instance fields once, but each object gets its own copies??? //...declare methods, too... Each Object Has Its Own Instance Fields You declare the instance fields once, but each object gets its own copies??? Remember: the class is like a blueprint or pattern. It says how to make objects: A car blueprint shows a steering wheel, but each car gets its own steering wheel. A dress pattern shows one pocket, but each dress has its own pocket. Celebrity class shows String variables for name and description, but each object gets its own. Accessing Instance Fields If the instance fields are public, users of the class can treat them like normal variables: prof.name = Alan ; prof.description = dignified ; (If you say neither public nor private, the default is called package access, which is basically public for our purposes.) Keep Instance Fields Private! If the instance fields are public, users of the class can treat them like normal variables: prof.name = Alan ; prof.description = dignified ; If the instance fields are public, users of the class can misuse or mess up your instance fields! Good style is to keep them private. Keep Instance Fields Private! Good style is to keep them private. If the instance fields are private, users of the class can t access them. How do they use your class? 10
Accessor and Mutator Methods Questions? Good style is to keep them private. If the instance fields are private, users of the class can t access them. How do they use your class? The standard Java convention is to provide public methods to access (read) or mutate (modify) the instance fields. E.g., getname() or setname(string name) You can control access to fields this way. Constructors What happens if the user forgets to set the instance fields? Constructors What happens if the user forgets to set the instance fields? It s best to supply a default for instance fields at the moment the object is created. This way, all objects are always properly created. We do this by writing our own code for the constructor methods. Constructors To create a constructor method, declare a method with: the same name as the class no return type (at all, not even void) parameters, if you want Put code in the method to initialize the instance fields. Constructors public Celebrity() { this.name = Joe Schmoe"; this.description = forgettable"; this.salary = new BigInteger( 0 ); 11
Constructors public Celebrity() { name = Joe Schmoe"; description = forgettable"; salary = new BigInteger( 0 ); Using vs. Designing Classes Using a Class Read API. Get and use objects. Instantiate objects with new ClassName() Call methods to get things done. Access public things only. Designing a Class Write API. Provide blueprint/pattern for objects. Define constructor ClassName() { Implement methods. Say how to actually do things. Decide what is public and what is private. Questions? 12