Presentation is loading. Please wait.

Presentation is loading. Please wait.

Barb Ericson Georgia Institute of Technology June 2005

Similar presentations


Presentation on theme: "Barb Ericson Georgia Institute of Technology June 2005"— Presentation transcript:

1 Barb Ericson Georgia Institute of Technology June 2005
Creating Classes Barb Ericson Georgia Institute of Technology June 2005 Georgia Institute of Technology

2 Georgia Institute of Technology
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 Georgia Institute of Technology
Class Definition Each class is defined in a file With the same name as the 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 The order of the items in a class definition doesn’t matter to Java. Usually you group the fields together and the constructors together, and the methods together. You can actually put the methods first, then the constructors, and then the fields. Georgia Institute of Technology

6 Georgia Institute of Technology
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 Georgia Institute of Technology
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 Georgia Institute of Technology
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 Georgia Institute of Technology
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; } The name field will start off with a value of null since strings are objects. The gradeArray field will also start off with a value of null since arrays are objects. 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? you may not get the exact same thing Georgia Institute of Technology

11 Georgia Institute of Technology
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 The compiler will call the toString method on any object you print with System.out.println(). Georgia Institute of Technology

12 Georgia Institute of Technology
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 A declaration of public class Student Is the same as public class Student extends Object Georgia Institute of Technology

14 Georgia Institute of Technology
Getting the Class An object keeps a reference to the class that created it You can get this class with getClass(); Each class keeps a reference to the parent class 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; } Test this new method: Student studentObj = new Student(); System.out.println(studentObj); Georgia Institute of Technology

16 Georgia Institute of Technology
Constructors Are used to initialize the fields of an object To other than the default values or assigned value 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

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

18 Georgia Institute of Technology
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

19 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); When we create student1 the no-argument constructor will be called since we haven’t passed any parameters. When we create student2 the constructor will be called that takes a string. Georgia Institute of Technology

20 Georgia Institute of Technology
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; Georgia Institute of Technology

21 Georgia Institute of Technology
Debuggers You can use a debugger to find the cause of bugs (errors in your program) A moth caused one bug 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

22 Georgia Institute of Technology
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

23 Georgia Institute of Technology
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 All debuggers let you set breakpoints. Georgia Institute of Technology

24 Georgia Institute of Technology
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

25 Georgia Institute of Technology
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

26 Georgia Institute of Technology
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 Remember that in DrJava if you type something without a semicolon at the end it will print the value of the expression. Georgia Institute of Technology

27 Georgia Institute of Technology
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

28 Georgia Institute of Technology
Challenge 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

29 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

30 Georgia Institute of Technology
Challenge 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 Add to the toString method a call to this method Use the debugger to check that this is working correctly Stop in the getAverage method Georgia Institute of Technology

31 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 Georgia Institute of Technology

32 Accessors and Modifiers
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 public returnType setFieldName(type name); public void setName(String theName) {this.name = theName; } Georgia Institute of Technology

33 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

34 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

35 Georgia Institute of Technology
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

36 Georgia Institute of Technology
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

37 Georgia Institute of Technology
Challenge 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

38 Georgia Institute of Technology
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 One of the reasons why we use DrJava is to let students use the interactions pane to try things out without having to use a main. Many books start with a main method but don’t ever explain it. Georgia Institute of Technology

39 Georgia Institute of Technology
Main Method Add a main method to Student Do it in what you have been doing in the interactions pane 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

40 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

41 Georgia Institute of Technology
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

42 Georgia Institute of Technology
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. * Barb Ericson */ public class Student Georgia Institute of Technology

43 Georgia Institute of Technology
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 theName the new name to use true if success else false */ public boolean setName(String theName) Add comments to constructors that are like the method comments. Just realize the constructors don’t return anything. Georgia Institute of Technology

44 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

45 Georgia Institute of Technology
Challenge 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

46 Georgia Institute of Technology
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

47 Georgia Institute of Technology
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 UML means Uniform Modeling Language. This diagram shows that both the Student class and ClassPeriod class inherit from Object and that a ClassPeriod object has 0 to many Student objects associated with it. It also shows that a Student object has 5 to 8 ClassPeriod objects associated with it. Shows inheritance Has a or association Georgia Institute of Technology

48 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

49 Georgia Institute of Technology
Challenge 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

50 Georgia Institute of Technology
Challenge Add constructors to ClassPeriod Add the no argument constructor Add a constructor that takes the teacher’s name and the period number Remember that constructors are declared as public ClassName(paramList) { } Georgia Institute of Technology

51 Add Accessors and Modifiers
Add methods to get and set the fields in the class period public String getTeacherName() { return this.teacherName; } public void setTeacherName(String theName) this.teacherName = theName; Georgia Institute of Technology

52 Georgia Institute of Technology
Override toString Add the following method to ClassPeriod public String toString() { } Add code to the method to return a String with the teacher’s name, the period number, and the number of students in the class period The length of the array isn’t a count of the actual students Find out how many in the array are not null Georgia Institute of Technology

53 Georgia Institute of Technology
Summary Object-oriented programs Have interacting objects Classes define and create objects The contain the fields, constructors, and methods Some methods are called accessor and modifier methods since they give you access to private fields and let you modify private fields A class inherits methods from a parent class Georgia Institute of Technology


Download ppt "Barb Ericson Georgia Institute of Technology June 2005"

Similar presentations


Ads by Google