Barb Ericson Georgia Institute of Technology June 2005

Slides:



Advertisements
Similar presentations
TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Advertisements

Georgia Institute of Technology DrJava Appendix A Barb Ericson Georgia Institute of Technology May 2006.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
CPSC1301 Computer Science 1 Overview of Dr. Java.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Georgia Institute of Technology Manipulating Pictures, Arrays, and Loops Barb Ericson Georgia Institute of Technology August 2005.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CreatingSubclasses1 Barb Ericson Georgia Institute of Technology Dec 2009.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
Georgia Institute of Technology Creating Classes part 4 Barb Ericson Georgia Institute of Technology May 2006.
CreatingClasses-SlideShow-part41 Creating Classes part 4 Barb Ericson Georgia Institute of Technology Dec 2009.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Georgia Institute of Technology Creating Classes part 2 Barb Ericson Georgia Institute of Technology June 2006.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
Georgia Institute of Technology More on Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Information and Computer Sciences University of Hawaii, Manoa
Appendix A Barb Ericson Georgia Institute of Technology May 2006
Manipulating Pictures, Arrays, and Loops part 2
Manipulating Pictures, Arrays, and Loops part 2
Appendix A Barb Ericson Georgia Institute of Technology May 2006
Some Eclipse shortcuts
Manipulating Pictures, Arrays, and Loops part 3
Testing and Debugging.
Data types and variables
Creating and Modifying Text part 2
Barb Ericson Georgia Institute of Technology Dec 2009
Important terms Black-box testing White-box testing Regression testing
Important terms Black-box testing White-box testing Regression testing
CS Week 13 Jim Williams, PhD.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Manipulating Pictures, Arrays, and Loops part 2
Manipulating Pictures, Arrays, and Loops part 2
Java Programming with BlueJ
Debugging with Eclipse
Object Oriented Programming (OOP) LAB # 8
CS1316: Representing Structure and Behavior
Defining Classes and Methods
Introduction to Java part 2
CS1316: Representing Structure and Behavior
Manipulating Pictures, Arrays, and Loops part 3
Teaching Java using Turtles part 3
Introduction to Processing Digital Sounds part 3
Barb Ericson Georgia Institute of Technology Oct 2005
Workshop for Programming And Systems Management Teachers
Applying OO Concepts Using Java
Manipulating Pictures, Arrays, and Loops
Debugging “Why you were up till 2AM”
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Introduction to Java part 2
More on Creating Classes
Manipulating Pictures, Arrays, and Loops
Creating and Modifying Text part 3
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Barb Ericson Georgia Institute of Technology Oct 2005
More on Creating Classes part 3
References Revisted (Ch 5)
CMPE212 – Reminders Assignment 2 due next Friday.
Corresponds with Chapter 5
Debugging with Eclipse
Workshop for Programming And Systems Management Teachers
Presentation transcript:

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

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 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 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

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

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/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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 theName the new name to use * @return 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

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

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

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

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

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

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

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

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

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

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