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,

Slides:



Advertisements
Similar presentations
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Advertisements

L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
TOPIC 5 INTRODUCTION TO PICTURES 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B.
TOPIC 13 OBJECTS IN MEMORY, PASSING PARAMETERS 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial.
Road Map Introduction to object oriented programming. Classes
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
CS 106 Introduction to Computer Science I 03 / 19 / 2008 Instructor: Michael Eckmann.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Constructors A constructor is a method that creates an object in Java. It does not return anything and it is not void. It’s only purpose is to create an.
Introduction to Programming Writing Java Beginning Java Programs.
TOPIC 3 INTRODUCTION TO PROGRAMMING 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CS 106 Introduction to Computer Science I 03 / 19 / 2007 Instructor: Michael Eckmann.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
TOPIC 11 RETURNING VALUES FROM METHODS PICTURE TRANSFORMATIONS 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach.
Georgia Institute of Technology Manipulating Pictures, Arrays, and Loops Barb Ericson Georgia Institute of Technology August 2005.
TOPIC 6 MODIFYING PICTURES USING LOOPS 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
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.
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Introduction to Programming Writing Java Beginning Java Programs.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
CS 106 Introduction to Computer Science I 10 / 29 / 2007 Instructor: Michael Eckmann.
Computer Science 111 Fundamentals of Computer Programming I Working with our own classes.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Peter Centgraf.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Creating Your Own Classes
Intro To Classes Review
Chapter 4: Writing Classes
Manipulating Pictures, Arrays, and Loops part 2
Barb Ericson Georgia Institute of Technology Oct 2005
Manipulating Pictures, Arrays, and Loops
Barb Ericson Georgia Institute of Technology June 2005
More on Creating Classes
Barb Ericson Georgia Institute of Technology Oct 2005
Presentation transcript:

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, and instructor materials prepared by B. Ericson.

Outline 2  Identifying objects and classes  Defining a class  Defining attributes  Also called fields  Also called instance variables  Defining constructors  Overloading constructors  Defining methods

Recall: Java is Object-Oriented  In Java, the focus is on objects  Objects are entities that can do actions or be acted upon in a Java program  All objects have Properties These are the data about an object In Java we call them attributes or fields Behaviors (actions) In Java they are implemented as methods  Examples: Picture objects, Picture methods

Objects and Classes 4  Every object belongs to a specific class  Objects that belong to the same class share properties and behaviors  Example: we can invoke the methods of the Picture class on any Picture object  We can think of a class as being a template or pattern or model for objects of that class

Objects and Classes 5  Object-oriented programs consist of interacting objects Which are defined by classes And created by other classes  Example:  Picture class defines the attributes of a Picture object and the methods that can be invoked on a Picture object  We can write programs to perform some task, that create and use objects of the Picture class

Object-Oriented Design 6  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 do they need to know to do the task? What attributes describe them? (fields)  What actions do they need? What can they do / what can be done to them? (methods)

Identifying the Objects and Classes 7  Say that we want to write a program to track the grades of students  One way to start is to identify the nouns  We get grades and student  Then we decide if something should be a class (template for objects) or a field (data) Does it have more than one piece of data associated with it?  A student has a name and grades, so it should be defined by a class

Identifying the Objects and Classes 8  Decide on the fields (attributes) of the class:  A particular student has a name, which is a string grades, which are numbers these will be fields of the student class  Decide on the actions (methods) to be performed on the student objects  We need to analyze what we might want to do with the data  Examples: Show the student name and grades Get the average of the grades for the student  We will do this example in detail later

Class Definition 9  A class definition consists of  Field (attribute) definitions  Constructor definitions  Method definitions  A class definition is stored in a file  With the same name as the class  With a.java extension on the file  Examples: Turtle.java, Picture.java

Class Definition – Class Names 10  Class names  Should be singular Why? we are describing an object of that type Examples: Turtle, Picture, Student  Start with an uppercase letter  The rest of the word is lowercase, except the first letter of each additional word should be uppercase Examples: ColorChooser, SimpleTurtle

Class Definition - Syntax 11  The syntax for a class definition is: visibility class ClassName { field (=attribute) definitions constructor definitions method definitions }

Class Definition - Attributes 12  Field (attribute) definitions  Example: the SimpleTurtle class of our textbook declares many attributes for an object of this class, some of which are: int width = 15; // width of this turtle int height = 18; // height of this turtle int xPos = 320; // x coordinate of current position int yPos = 240; // y coordinate of current position  Attributes can be initialized to default values  What is SimpleTurtle? See next slide

Brief Digression: Inheritance 13  In our textbook examples, we have used the class Picture  The intention is that we can add methods to this class  The authors have put the parts that they do not want changed into a class called SimplePicture, and Picture is just an “extension” of SimplePicture  We say Picture inherits from SimplePicture and that SimplePicture is the parent of Picture  An object of type Picture is also of type SimplePicture, so it has its attributes and methods  This is the structure of Turtle and SimpleTurtle also

Class Definition - Attributes 14  Syntax for attribute/field definition: visibility type name; visibility type name = expression;  We usually use private for the visibility  The type is a primitive type or a class name  Field names start with a lowercase letter  Examples: private int width = 15; private int height = 18;

Class Definition - Attributes 15  Why are attributes usually private? So that other classes cannot access them directly (i.e. can only access them through methods of the class)  Example: getRed(), setRed() methods of the Pixel class Users of the Pixel class do not need to know how/where the red value for a pixel is stored In fact, the representation for the colors of a pixel could change in a new version of Pixel.java, and users do not even need to know that

Class Definition - Attributes 16  The variables that we define for the attributes are also known as instance variables  Why? They are variables that describe an instance of the class, i.e. an object of the class  Example: width, height, xPos, yPos, etc. are instance variables for the SimpleTurtle class

Class Definition - Constructors 17  Constructor definitions  A constructor is a special method that is called automatically when an object is created with the new operator  Its purpose is to initialize the attributes of an object when the object is created  Examples: World world1 = new World(); Turtle turtle1 = new Turtle(100,200, world1); Turtle turtle2 = new Turtle(world1);  Constructors have the same name as the class name

Class Definition - Constructors 18  Syntax for a constructor definition visibility ClassName (paramList) { // assign values to instance variables }  Note that constructor has no return type  Example: constructor that initializes turtle start position to the parameter values public SimpleTurtle(int x, int y) { xPos = x;// initialize xPos yPos = y; // initialize yPos … }

Class Definition - Constructors 19  Default Field Values  If a constructor does not initialize an instance variable to some specific value, it has as its default value the value from the attribute definition  Example: int width = 15;// width of this turtle int height = 18;// height of this turtle  When an object is created, it has its own set of instance variables

Objects and their Attributes 20  Example: World world1 = new World(); Turtle turtle1 = new Turtle(100,200, world1); Turtle turtle2 = new Turtle(world1); turtle1 turtle2 width height xPos yPos … width height xPos yPos …

Class Definition - Methods 21  Method definitions  Recall the syntax for defining a method visibility returnType name(parameterList) { body of method }  Example from Picture class: public void changeRed(double howMuch) { Pixel[] pixelArray = this.getPixels(); // etc. }

Example: Student Class 22  We will now define a class Student that models keeping track of a student’s grades  A Student class could be much more complex  We will define a very simple class for now

Class Definitions in DrJava 23  To define the Student class  Click on the New button in DrJava  Type in the Definitions pane: public class Student { // fields, constructors, methods go here }  Save it in Student.java

Example: Student Class 24  A student should have a name and some grades associated with it, so the name and grades should be fields in our Student class  What type should we use for each of these?  The field name can be a String  We will have a collection of grades, and each can have a decimal point in it So, we will use double as the type Stored in an array of grades

Example: Student Class - Fields 25 public class Student { // fields (attributes) private String name; private double[ ] gradeArray; … }

Example: Student Class - Constructor 26  Add the constructor definition to the Student class after the field definitions: public Student(String theName) { this.name = theName; }

Class Definitions – Using Attributes 27  Within the methods of a class, you can access the attributes (and other methods) of the class directly  Example: constructor on previous slide public Student(String theName) { this.name = theName; }  We could also write this as public Student(String theName) { name = theName; }  The "this" is implicit here

Example: Create a Student object 28  Suppose a new Student object is created in some program by Student student1 = new Student(“Student 1”);  What is its name field initialized to?  What is its gradeArray field initialized to? Why? student1 name gradeArray “Student 1"

Constructor Overloading 29  You can have more than one constructor  As long as the parameter lists are different  This is called constructor overloading  We have seen method overloading before, in the methods we wrote for the Picture class

Example: Another Constructor 30  Add another constructor to the Student class that takes both the name and an array of grades as parameters: public Student(String theName, double[] theGrades) { this.name = theName; this.gradeArray = theGrades; }

Example: Create a Student object 31  We could create another new Student object in some program by: double [ ] grades = {75,85,73,92,81}; Student student2 = new Student(“Student 2", grades); student2 grades name gradeArray “Student 2" 75,85,73,92,81

Example: Student Class - Methods 32  What methods might we want in the Student class?  We need to decide what we might want to do with the data:  Show the student name and grades  Get the average of the grades for the student

Example: toString Method 33  It is conventional to have a toString() method in every class  It returns a string containing the object’s data  Which can then be printed public String toString() { String s = “Student ” + this.name + “ has grades ”; for (int i = 0; i < this.gradeArray.length; i ++) s = s + this.gradeArray[i] + “ ”; return s; }

Example: toString Method 34  We can now print a student object’s data using System.out.println(student2.toString());  We can also do this using System.out.println(student2);  Why? Java automatically invokes the toString() method for the class of which student2 is an object If that class does not have a toString() method, Java will use the toString() method of the Object class, which is the parent class of every other class This does not, however, provide useful information about the data of the object

Example: toString Method 35  Now consider our previous example object: Student student1 = new Student(“Student 1”);  What is its name field initialized to?  What is its gradeArray field initialized to?  What will happen now if we type System.out.println(student1.toString());  How can we handle that?

Example: Revised toString Method 36 public String toString() { String s = “Student ” + this.name; if (this.gradeArray != null) { s = s + “ has grades ”; for (int i = 0; i < this.gradeArray.length; i ++) s = s + this.gradeArray[i] + “ ”; } return s; }

Example: Calculate Grade Average 37  To calculate an average:  Sum the grades  Divide by the number of grades (the length of the grade array)  We need to be careful of:  A null gradeArray  A 0 length gradeArray

Example: getAverage Method 38  Create a method getAverage that calculates and returns the average of the grades in the grade array  Algorithm:  Return 0 if the grade array is null  Return 0 if the grade array length is 0  Otherwise return sum of grades / number of grades

The getAverage Method 39 public double getAverage() { double average = 0.0; if (this.gradeArray != null && this.gradeArray.length > 0) { double sum = 0.0; for (int i = 0; i < this.gradeArray.length; i++) { sum = sum + this.gradeArray[i]; } average = sum / this.gradeArray.length; } return average; }

Example: Testing our Student class 40  Try this in the Interactions pane: Student student1 = new Student(“Student 1"); System.out.println(student1.toString()); System.out.println("Average = " + student1.getAverage()); double [] grades = {75,85,73,92,81}; Student student2 = new Student(“Student 2“, grades); System.out.println(student2.toString()); System.out.println("Average= " + student2.getAverage());

Testing equality  Suppose we have another student Student student3 = new Student(“Student 2“, grades);  Do we mean that student2 and student3 are the same student?  They are both reference variables, but to different Student objects  However, the two objects have the same contents  This is state equality, as opposed to identity equality 41

Testing equality  Testing identity equality is done through the expression (student1 == student2)  Important use: testing if a Student object is null if (student1 == null) System.out.println(“Student object not initialized”);  To test state equality (between students), one writes a method public boolean equals(Student otherStudent) that returns true if the attributes are the same  Not easy to write correctly 42

Rules to keep in mind  Make sure that you’re not trying to access some methods or attributes of a null object  Make sure that you’re not trying to access the length of a null array  Concretely: test whether they are null or not  If you need to test whether two arrays have the same contents, you should not use == 43

Testing state equality for students public boolean equals(Student otherStudent) if (otherStudent == null) return false; // the current student cannot be null // first we check if the names are the same if ( ! this.name.equals(otherStudent.name) ) return false; // equals exists in the String class // to compare the arrays of grades, we first deal // with the case where one could be null if (this.gradeArray == null && otherStudent.gradeArray == null) return true; 44

Testing state equality for students if (this.gradeArray == null || otherStudent.gradeArray == null) return false; // so now, none of the arrays is null if (this.gradeArray.length != otherStudent.gradeArray.length) return false; // now, both arrays have the same length for (int i = 0; i < this.gradeArray.length; i++) if (this.gradeArray[i] != otherStudent.gradeArray[i]) return false; return true; } 45

Summary 46  Identifying objects and classes  Defining a class  Defining attributes  Also called fields  Also called instance variables  Defining constructors  Overloading constructors  Defining methods  Understanding equality