1 / 54

Creating Classes

Creating Classes. Barb Ericson Georgia Institute of Technology July 2005. Learning Goals. Computing concepts Identifying objects and classes Declaring a class Declaring a constructor Overloading constructors Declaring fields Creating accessors and modifiers Declaring a main method

Download Presentation

Creating Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Creating Classes Barb Ericson Georgia Institute of Technology July 2005 Georgia Institute of Technology

  2. Learning Goals • Computing concepts • Identifying objects and classes • Declaring a class • Declaring a constructor • Overloading constructors • Declaring fields • Creating accessors and modifiers • Declaring a main method • Javadoc comments Georgia Institute of Technology

  3. Identifying Objects and Classes • Object-oriented programs • Consist of interacting objects • Which are defined by and created by classes • To identify the objects in a task • What are the things that are doing the work or being acted upon? • How do you classify them? • What data (fields) do they need to know to do the task? • What procedures (methods) do they need? Georgia Institute of Technology

  4. Identifying the Objects and Classes • Say that we want to write a program to track the grades of students. • One way to start is to underline the nouns • grades, student • Grades is a list of numbers that belongs to a student • Simple data like numbers and strings are fields in a class • So this would be a field in a student class • A student has grades and a name • So it needs to be a class • With fields for grades and name Georgia Institute of Technology

  5. Class Definition • Each class is defined in a file • With the same name as the class: Class.java • Class names • Are singular (Student not Students) • Start with an uppercase letter • The rest of the word is lowercase • Uppercase the first letter of each additional word • The syntax for a class definition is: • visibility class Name {} • Inside the class definition goes: • Fields, constructors, and methods Georgia Institute of Technology

  6. Class Declaration • To declare a Student class • Click on the New button in DrJava • Type in: public class Student { } • Save it in Student.java • Click on File then Save • Click the Compile All button to compile it Georgia Institute of Technology

  7. Student Fields • A student should have a name and some grades • What type should we use for each of these? • The Field name can be a String object • Maybe we will have at most 20 grades and they can have a decimal point in them • Since they can have a decimal point let’s use double as the type • We could name them grade1, grade2, grade3 … • Or, we can use an array Georgia Institute of Technology

  8. Declaring Fields • Syntax • visiblity type name; • visibility type name = expression; • Usually use private for the visibility • So that other classes can’t access it directly • The type is any of the primitive types, a class name , or an interface name • Arrays are declared with [] after the type or after the name • type[] name; or type name[]; • Names start with a lowercase letter • The first letter of each additional word is uppercased Georgia Institute of Technology

  9. Default Field Values • If you don’t specify an initial value for a field • It will get one anyway when it is created • Numbers = 0 • Objects = null (not referring to any object yet) • boolean = false public class Student { /////////////// fields /////////////// private String name; private double[ ] gradeArray; } Initial value will be null Georgia Institute of Technology

  10. Testing the Student Class • Add the fields to the Student class definition and compile it • Try the following in the interactions pane • Student studentObj = new Student(); • System.out.println(studentObj); • What happens? • Student@2bd3a • you may not get the exact same thing Georgia Institute of Technology

  11. What Happened? (Inherited Methods) • When you executed • System.out.println(studentObj); • The class Student was checked for a toString method • Since it didn’t have one the parent class was checked for a toString method • The one in Object was executed • Which prints the hash code for the object • The Student class inherited the toString method from the Object class Georgia Institute of Technology

  12. How Inheritance Works • When a method is invoked on an object • We first check for that method in the object that defines the object’s class • If it isn’t there we look in the parent of that class Georgia Institute of Technology

  13. All Classes Inherit from Object • If you don’t specify the parent class when you declare a class • The class with inherit from java.lang.Object • You can specify the parent class • Add extends Parent to the class declaration public Student extends Object • A declaration of public class Student • Is the same as public class Student extends Object Georgia Institute of Technology

  14. Getting the Class • An object keeps a reference to the class that created it • You can get this class with • Class currClass = obj.getClass(); • Each class keeps a reference to its parent class • You can get this class with • Class parentClass = currClass.getSuperclass(); • Try: • Student student1 = new Student(); • Class studentClass = student1.getClass(); • Sytem.out.println(studentClass); • Class parentClass = studentClass.getSuperclass(); • System.out.println(parentClass); Georgia Institute of Technology

  15. Overriding an Inherited Method • If a class defines a method with the same name and parameter list as an inherited method • This method will be called instead of the parent method • To override Object’s toString add this one to Student: public String toString() { return “Student object named “ + this.name; } Georgia Institute of Technology

  16. Testing toString • Compile Student.java • Type the following in the interactions pane Student studentObj = new Student(); System.out.println(studentObj); • What do you get this time? Georgia Institute of Technology

  17. Constructors • Are used to initialize the fields of an object • To other than the default values or assigned values • You can have more than one constructor • As long as the parameter lists are different • This is called overloading constructors • Syntax • visibility ClassName(paramList) {} • Example public Student(String theName) { this.name = theName;} Georgia Institute of Technology

  18. Add a Constructor • Add the following after the field declarations to Student.java: public Student(String theName) { this.name = theName; } • Compile and test • Student student1 = new Student(); • System.out.println(student1); Georgia Institute of Technology

  19. Why did you get an Error? • We hadn’t declared any constructors before we added this one • But a constructor is called each time a new object is created • We didn’t provide one so the compiler added a no-argument constructor • One that takes no parameters and leaves the fields with their default or assigned values • But once you add a constructor • The compiler will not add any for you Georgia Institute of Technology

  20. Adding a No-Argument Constructor • Add the following constructor to the Student class • public Student() {} • Now test it again with: • Student student1 = new Student(); • System.out.println(student1); • Also try: • Student student2 = new Student(“Sue Clark”); • System.out.println(student2); Georgia Institute of Technology

  21. Tracing Execution • One way to trace what is happening in your program is • To add System.out.println() statements • Add these to print out the value of the current object’s name before and after the name is initialized in the constructor that takes a name • System.out.println(this.name); • this.name = theName; • System.out.println(this.name); Georgia Institute of Technology

  22. Debuggers • You can use a debugger to find the cause of bugs (errors in your program) • A moth caused one bug • http://www.jamesshuggins.com/h/tek1/first_computer_bug.htm • And to trace execution to see what is happening • Which constructor is executed or what method is executed • What values are in the fields Georgia Institute of Technology

  23. DrJava’s Debugger • Click on Debugger in the menu • Then check the Debug Mode checkbox Stack and Threads Area Watches and Breakpoints Area Check values here Georgia Institute of Technology

  24. Setting a Breakpoint • When you use a debugger you often want to set places to stop execution • Each place to stop at is a breakpoint • Once execution has stopped there • You can check the value of parameters and fields • To set a breakpoint • Right click on a line of code • Pick “Toggle Breakpoint” • It will be highlighted in red Georgia Institute of Technology

  25. Showing a Breakpoint • Lines with breakpoints are highlighted in red in DrJava • Set a breakpoint at the line that sets the name in the constructor that takes a name as a parameter Georgia Institute of Technology

  26. Testing a Breakpoint • Type the following in the interactions pane • Student student1 = new Student(“Sue Clark”); • Execution should stop at the breakpoint • And the color change to blue Georgia Institute of Technology

  27. Checking Values • Execution stops before the breakpoint line is executed • So the name hasn’t been set to the passed value yet • Check this by printing out the value of it in the interactions pane • this.name • this.gradeArray • Then click on the Step Over button • To let the current line of code be executed • And check the values again Georgia Institute of Technology

  28. Debugging Options • Step Over • Execute the current line of code and then stop again before you execute the next line of code • Step Into • If the line of code that we are stopped at has a method call in it stop at the first line in the called method • Resume • Continue execution at the current point • Until the next breakpoint • Or the program ends • Step Out • Execute the rest of the current method and stop at the first line after the call to this method • You can quit debugging by clicking on the X Georgia Institute of Technology

  29. Adding a Constructor Exercise • Create another constructor in the Student class • That takes both the name and an array of grades • To create an array of doubles for the grade array use: • double[] gradeArray = {90.3, 85.2, 89.7, 95.3}; • Use the debugger to check what happens during execution of this constructor Georgia Institute of Technology

  30. Calculating the Grade Average • Now that a student has an array of grades one of the things we probably would like is to • Show the average when you print information about the student • To calculate an average • Sum the grades • Divide by the number of grades • The length of the array • We need to be careful of • A null gradeArray • A 0 length gradeArray Georgia Institute of Technology

  31. Create a Method Exercise • Create a method (getAverage) that will calculate and return the average of the grades in the grade array • It will return 0 if the grade array is null • It will return 0 if the grade array length is 0 • Otherwise it will return the sum of the grades / the number of grades • Modify the toString method to call the getAverage method and add the average to the returned string • Use the debugger to check that this is working correctly • Stop in the getAverage method Georgia Institute of Technology

  32. Accessing Fields from Other Classes • Fields are usually declared to be private • So that code in other classes can’t directly access and change the data • Try this in the interactions pane • Student student1 = new Student(“Sue Clark”); • System.out.println(student1.name); • You will get an exception • Short for exceptional event – error • Outside classes can not use object.field to access the field value • Unless it is declared with public visibility Georgia Institute of Technology

  33. Accessors and Modifiers • Accessors • Are public methods that return data • In such a way as to protect the data for this object • Syntax public fieldType getFieldName() • Example public String getName() { return this.name;} • Modifiers • Are public methods that modify data • In such a way as to protect the data for this object • Syntax public returnType setFieldName(type name); • Example public void setName(String theName) {this.name = theName; } Georgia Institute of Technology

  34. Creating Student Accessors • Add a method to get the name public String getName() { return this.name;} • What about a method to get the array of grades? • If someone gets the array they can directly change the grades in the array • It is safer to return the grade at an index • Then other classes can’t directly change the grade public double getGrade(int index) { return this.gradeArray[index];} Georgia Institute of Technology

  35. Creating Student Modifiers • We need public methods • That let other classes ask for the grade to change or the name to change • Our class is responsible for making sure this only happens in such a way • as to keep the data valid and not cause errors • Setting a grade • The grade must be >= 0 • The gradeArray must not be null • The index must be < the length of the array • Setting a name • We can decide if this can be changed or not once it isn’t null Georgia Institute of Technology

  36. Name Modifier • Setting the name only if currently null public boolean setName(String theName) { if (this.name == null) { this.name = theName; return true; } else return false; } Georgia Institute of Technology

  37. Grade Modifier public boolean setGrade(int index, double newGrade) { if (newGrade < 0 || this.gradeArray == null || this.gradeArray.length <= index || index < 0) return false; else { this.gradeArray[index] = newGrade; return true; } } Georgia Institute of Technology

  38. Add a Field Exercise • Add a picture field to student that will hold a Picture object of a student • Add an accessor to get the value of this field • Add a modifier to set the value of this field • Add a method (show) that will show the picture • If it isn’t null Georgia Institute of Technology

  39. Adding a Main Method • We have been typing stuff in the interactions pane in DrJava • To try out Java code and to try methods • Most development environments make you write a main method to start execution • DrJava allows this too • Each class can have a main method declared as follows: • public static void main(String[] args) • It is public so that it can be called by other classes • It is static because no object of the class exists when it is executed • It doesn’t return anything so the return type is void • You can pass several arguments to the main method and these are put in an array of strings Georgia Institute of Technology

  40. Main Method • Add a main method to Student • Put the statements that you have been doing in the interactions pane in the main method public static void main(String[] args) { Student student1 = new Student(); System.out.println(student1); Student student2 = new Student(“Sue Clark”); System.out.println(student2); } Georgia Institute of Technology

  41. Execute the Main Method • In DrJava you can run the main method in the class that is displayed in the definitions pane • By clicking on Tools then Run Document’s Main Method (or press key F2) • It will do • java Student • In the interactions pane • Which executes the main in the Student class Georgia Institute of Technology

  42. Comments • You should add comments to your code • To make it easier to read and change • Comments are ignored by the complier • Not added to the byte codes • Java has 3 kinds of comments • // comment ends at the end of this line • /* comment ends with next */ • /** Javadoc comment that ends with */ • can be used by the javadoc utility to create HTML documentation Georgia Institute of Technology

  43. Javadoc Comments • Add a comment before the class definition • That explains the purpose of this class • And says who wrote it • @author Barb Ericson /** * Class that describes a student. A student has a * name and an array of grades. You can get * information about a student such as her/his * name and grade average. * * @author Barb Ericson */ public class Student Georgia Institute of Technology

  44. Method Comments • Add a comment before each method • What the parameters are • @param name info • What is returned • @return info /** * Method to set the name for this student * @param theName the new name to use * @return true if success else false */ public boolean setName(String theName) Georgia Institute of Technology

  45. Generating Javadoc based HTML • In DrJava click on the Javadoc button • to create the HTML documentation • based on the Javadoc comments • This will generate HTML for all files in the same directory as all open files • Generates an index.html as a starting point Georgia Institute of Technology

  46. Javadoc Exercise • Add a class javadoc comment and method javadoc comments to the Student class • Execute Javadoc and check out the created documentation Georgia Institute of Technology

  47. Create a ClassPeriod • A teacher has students in each class period • Each period can have different students • For a class period we might want to know • The teacher’s name • The period number • The students in that period Georgia Institute of Technology

  48. UML Class Diagram • There is a standard way to diagram object-oriented classes • It is a UML class diagram • It shows the classes as boxes and the relationships between them Shows inheritance Has a or association Georgia Institute of Technology

  49. Creating a ClassPeriod class • We want fields for the • Teacher’s name • Period number • Students in the period • What type should each of these be? • A name can be a string • A period number can be an integer • The students in the period can be an array of Student objects • With a max of 35 students in a class period Georgia Institute of Technology

  50. Create a Class Exercise • Declare a new class ClassPeriod in the file ClassPeriod.java • Add the fields: • private String teacherName; • private int periodNumber; • private Student[] studentArray = new Student[35]; Georgia Institute of Technology

More Related