Creating Classes Barb Ericson Georgia Institute of Technology
Creating Classes Barb Ericson Georgia Institute of Technology June 2005 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
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 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
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
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 Georgia Institute of Technology
Class Declaration • To declare a Student class – Click on the New button in Dr. Java • 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
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 grade 1, grade 2, grade 3 … – Or, we can use an array 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
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[ ] grade. Array; } Initial value will be null Georgia Institute of Technology
Testing the Student Class • Add the fields to the Student class definition and compile it • Try the following in the interactions pane – Student student. Obj = new Student(); – System. out. println(student. Obj); • What happens? – Student@2 bd 3 a • you may not get the exact same thing Georgia Institute of Technology
Inherited Methods • When you executed – System. out. println(student. Obj); • The class Student was checked for a to. String method – Since it didn’t have one the parent class was checked for a to. String method • The one in Object was executed – Which prints the hash code for the object • The Student class inherited the to. String method from the Object class 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
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
Getting the Class • An object keeps a reference to the class that created it – You can get this class with • get. Class(); • Each class keeps a reference to the parent class – You can get this class with • get. Superclass(); • Try: – – – Student student 1 = new Student(); Class student. Class = student 1. get. Class(); Sytem. out. println(student. Class); Class parent. Class = student. Class. get. Superclass(); System. out. println(parent. Class); Georgia Institute of Technology
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 to. String add this one to Student: public String to. String() { return “Student object named “ + this. name; } 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 Class. Name(param. List) {} • Example public Student(String the. Name) { this. name = the. Name; } Georgia Institute of Technology
Add a Constructor • Add the following after the field declarations: public Student(String the. Name) { this. name = the. Name; } • Compile and test – Student student 1 = new Student(); – System. out. println(student 1); 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
Adding a No-Argument Constructor • Add the following constructor to the Student class – public Student() {} • Now test it again with: – Student student 1 = new Student(); – System. out. println(student 1); • Also try: – Student student 2 = new Student(“Sue Clark”); – System. out. println(student 2); 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 = the. Name; – System. out. println(this. name); 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 – http: //www. jamesshuggins. com/h/tek 1/first_co mputer_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
Dr. Java’s Debugger • Click on Debugger in the menu – Then check the Debug Mode checkbox Watches and Breakpoints Area Stack and Threads Area Check values here 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 Georgia Institute of Technology
Showing a Breakpoint • Lines with breakpoints are highlighted in red in Dr. Java • Set a breakpoint at the line that sets the name in the constructor that takes a name as a parameter Georgia Institute of Technology
Testing a Breakpoint • Type the following in the interactions pane – Student student 1 = new Student(“Sue Clark”); • Execution should stop at the breakpoint – And the color change to blue 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. grade. Array – 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
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
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[] grade. Array = {90. 3, 85. 2, 89. 7, 95. 3}; – Use the debugger to check what happens during execution of this constructor Georgia Institute of Technology
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 grade. Array – A 0 length grade. Array Georgia Institute of Technology
Challenge • Create a method (get. Average) 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 to. String method a call to this method • Use the debugger to check that this is working correctly – Stop in the get. Average method Georgia Institute of Technology
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 student 1 = new Student(“Sue Clark”); – System. out. println(student 1. 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
Accessors and Modifiers • Accessors – Are public methods that return data • In such a way as to protect the data for this object • Syntax public field. Type get. Field. Name() • Example public String get. Name() { return this. name; } • Modifiers – Are public methods that modify data • In such a way as to protect the data for this object • Syntax public return. Type set. Field. Name(type name); • Example public void set. Name(String the. Name) {this. name = the. Name; } Georgia Institute of Technology
Creating Student Accessors • Add a method to get the name public String get. Name() { 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 get. Grade(int index) { return this. grade. Array[index]; } Georgia Institute of Technology
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 grade. Array 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
Name Modifier • Setting the name only if currently null public boolean set. Name(String the. Name) { if (this. name == null) { this. name = the. Name; return true; } else return false; } Georgia Institute of Technology
Grade Modifier public boolean set. Grade(int index, double new. Grade) { if (new. Grade < 0 || this. grade. Array == null || this. grade. Array. length() <= index || index < 0) return false; else { this. grade. Array[index] = new. Grade; return true; } } 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
Adding a Main Method • We have been typing stuff in the interactions pane in Dr. Java – To try out Java code and to try methods • Most development environments make you write a main method to start execution – Dr. Java 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
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 student 1 = new Student(); System. out. println(student 1); Student student 2 = new Student(“Sue Clark”); System. out. println(student 2); } Georgia Institute of Technology
Execute the Main Method • In Dr. Java 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 F 2) • It will do – java Student – In the interactions pane – Which executes the main in the Student class 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
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
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 the. Name the new name to use * @return true if success else false */ public boolean set. Name(String the. Name) Georgia Institute of Technology
Generating Javadoc based HTML • In Dr. Java 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
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
Create a Class. Period • 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
UML Class Diagram • There is a standard way to diagram objectoriented 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
Creating a Class. Period 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
Challenge • Declare a new class Class. Period in the file Class. Period. java • Add the fields: – private String teacher. Name; – private int period. Number; – private Student[] student. Array = new Student[35]; Georgia Institute of Technology
Challenge • Add constructors to Class. Period – 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 Class. Name(param. List) { } Georgia Institute of Technology
Add Accessors and Modifiers • Add methods to get and set the fields in the class period public String get. Teacher. Name() { return this. teacher. Name; } public void set. Teacher. Name(String the. Name) { this. teacher. Name = the. Name; } Georgia Institute of Technology
Override to. String • Add the following method to Class. Period public String to. String() { } • 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
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
- Slides: 53