creating classes

54
Georgia Institute of Technology Creating Classes Barb Ericson Georgia Institute of Technology July 2005

Upload: melodie-cantu

Post on 02-Jan-2016

36 views

Category:

Documents


1 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Creating Classes

Georgia Institute of Technology

Creating Classes

Barb EricsonGeorgia Institute of Technology

July 2005

Page 2: Creating Classes

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

Page 3: Creating Classes

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?

Page 4: Creating Classes

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

Page 5: Creating Classes

Georgia Institute of Technology

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

Page 6: Creating Classes

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

Page 7: Creating Classes

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

Page 8: Creating Classes

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

Page 9: Creating Classes

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

Initial value will be null

Page 10: Creating Classes

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

Page 11: Creating Classes

Georgia Institute of Technology

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

Page 12: Creating Classes

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

Page 13: Creating Classes

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

public Student extends Object

• A declaration of public class Student

• Is the same aspublic class Student extends Object

Page 14: Creating Classes

Georgia Institute of Technology

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

Page 15: Creating Classes

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

Page 16: Creating Classes

Georgia Institute of Technology

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?

Page 17: Creating Classes

Georgia Institute of Technology

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) {}

• Examplepublic Student(String theName)

{ this.name = theName;}

Page 18: Creating Classes

Georgia Institute of Technology

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

Page 19: Creating Classes

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

Page 20: Creating Classes

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

Page 21: Creating Classes

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;– System.out.println(this.name);

Page 22: Creating Classes

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

Page 23: Creating Classes

Georgia Institute of Technology

DrJava’s Debugger

• Click on Debugger in the menu– Then check the Debug Mode checkbox

Watches and Breakpoints Area

Stack andThreads Area

Check values here

Page 24: Creating Classes

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

Page 25: Creating Classes

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

Page 26: Creating Classes

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

Page 27: Creating Classes

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

Page 28: Creating Classes

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

Page 29: Creating Classes

Georgia Institute of Technology

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

Page 30: Creating Classes

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

Page 31: Creating Classes

Georgia Institute of Technology

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

Page 32: Creating Classes

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– Unless it is declared with public visibility

Page 33: Creating Classes

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

Page 34: Creating Classes

Georgia Institute of Technology

Creating Student Accessors

• Add a method to get the namepublic 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 gradepublic double getGrade(int index) { return this.gradeArray[index];}

Page 35: Creating Classes

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

Page 36: Creating Classes

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;

}

Page 37: Creating Classes

Georgia Institute of Technology

Grade Modifierpublic 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; } }

Page 38: Creating Classes

Georgia Institute of Technology

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

Page 39: Creating Classes

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

Page 40: Creating Classes

Georgia Institute of Technology

Main Method

• Add a main method to Student– Put the statements that you have been doing

in the interactions pane in the main methodpublic static void main(String[] args){ Student student1 = new Student(); System.out.println(student1); Student student2 = new Student(“Sue Clark”); System.out.println(student2);}

Page 41: Creating Classes

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

Page 42: Creating Classes

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

Page 43: Creating Classes

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

Page 44: Creating Classes

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)

Page 45: Creating Classes

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

Page 46: Creating Classes

Georgia Institute of Technology

Javadoc Exercise

• Add a class javadoc comment and method javadoc comments to the Student class

• Execute Javadoc and check out the created documentation

Page 47: Creating Classes

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

Page 48: Creating Classes

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

Shows inheritance

Has a or association

Page 49: Creating Classes

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

Page 50: Creating Classes

Georgia Institute of Technology

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

Page 51: Creating Classes

Georgia Institute of Technology

Create a Class Exercise - Continued

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

{

}

Page 52: Creating Classes

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

Page 53: Creating Classes

Georgia Institute of Technology

Override toString

• Add the following method to ClassPeriodpublic 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

Page 54: Creating Classes

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 and fields from a parent class