CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.

Slides:



Advertisements
Similar presentations
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
Chapter 5 Defining Classes II Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming Lecture 17: – Linked Lists Copyright © 2008 Xiaoyan Li.
Road Map Introduction to object oriented programming. Classes
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
CS102--Object Oriented Programming
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
CS102--Object Oriented Programming Lecture 10: – Abstract Classes Copyright © 2008 Xiaoyan Li.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
CMSC 202 Classes and Objects: Reusing Classes with Composition.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CMSC 202 Classes and Objects: Reusing Classes with Composition.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Sahar Mosleh California State University San MarcosPage 1 The Class String There is no primitive type for strings in Java The class String is a predefined.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Slides prepared by Rose Williams, Binghamton University Chapter 4 Defining Classes I.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Static Methods Slides 2 to 15 only Static Methods A static method is one that can be used without a calling object A static method still belongs.
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
By Pius Nyaanga Momanyi
CMSC 202 Static Methods.
Inheritance 2nd Lecture
Chapter 6 Methods: A Deeper Look
Chapter 5 Defining Classes II
Implementing Non-Static Features
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Chapter 5 Defining Classes II
Defining Classes and Methods
Java Classes and Objects 4th Lecture
Chapter 4 Defining Classes I
Classes and Objects Static Methods
Defining Classes and Methods
Classes, Objects and Methods
Classes and Objects Reusing Classes with Composition
Chapter 4 Constructors Section 4.4
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li

Review: The String class Console output/input – System.out.print – System.out.println – System.out.printf – The Scanner class Flow of control – Branching – looping

Ten Important Questions about Classes in java: 1. What are the contents of a class? 2. Where are they placed within a class? 3. What are instance variables and local variables? 4. What is the difference between primitive type values and class type values? 5. Which operator do you need to create an object? 6. What is the meaning of the reserved word “this”? 7. When do you use the modifier public or private? 8. What is a constructor? How many constructors can a class have? 9. What are static methods and static variables? 10. What are reference variables and value variables?

Defining Classes: The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects will have – These data items and methods are sometimes called members of the object – Data items are called fields or instance variables Where can instance variable declarations and method definitions be placed within the class definition – Anywhere and in any order Local variables vs. instance variables 4-4 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Primitive Type Values vs. Class Type Values A primitive type value is a single piece of data A class type value or object can have multiple pieces of data, as well as actions called methods – All objects of a class have the same methods – All objects of a class have the same pieces of data (i.e., name, type, and number) – For a given object, each piece of data can hold a different value 4-5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The new Operator An object of a class is named or declared by a variable of the class type: ClassName classVar; The new operator must then be used to create the object and associate it with its variable name: classVar = new ClassName(); These can be combined as follows: ClassName classVar = new ClassName(); 4-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Instance Variables and Methods Instance variables can be defined as in the following two examples – Note the public modifier (for now): public String instanceVar1; public int instanceVar2; In order to refer to a particular instance variable, preface it with its object name as follows: objectName.instanceVar1 objectName.instanceVar2 4-7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The this Parameter All instance variables are understood to have. in front of them If an explicit name for the calling object is needed, the keyword this can be used – myInstanceVariable always means and is always interchangeable with this.myInstanceVariable 4-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The methods equals and toString Java expects certain methods, such as equals and toString, to be in all, or almost all, classes The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal" – Note: You cannot use == to compare objects public boolean equals(ClassName objectName) The purpose of the toString method is to return a String value that represents the data in the object public String toString() 4-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class It is considered good programming practice to make all instance variables private Most methods are public, and thus provide controlled access to the object Usually, methods are private only if used as helping methods for other methods in the class 4-10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Class Has Access to Private Members of All Objects of the Class Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object 4-11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Overloading Overloading is when two or more methods in the same class have the same method name To be valid, any two definitions of the method name must have different signatures – A signature consists of the name of a method together with its parameter list – Differing signatures must have different numbers and/or types of parameters 4-12 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Overloading and Automatic Type Conversion If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion The interaction of overloading and automatic type conversion can have unintended results In some cases of overloading, because of automatic type conversion, a single method invocation can be resolved in multiple ways – Ambiguous method invocations will produce an error in Java 4-13 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(anyParameters){code} – A constructor must have the same name as the class – A constructor has no type returned, not even void – Constructors are typically overloaded 4-14 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Constructors A constructor is called when an object of the class is created using new ClassName objectName = new ClassName(anyArgs); – The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator – This is the only valid way to invoke a constructor: a constructor cannot be invoked like an ordinary method If a constructor is invoked again (using new ), the first object is discarded and an entirely new object is created – If you need to change the values of instance variables of the object, use mutator methods instead 4-15 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

You Can Invoke Another Method in a Constructor The first action taken by a constructor is to create an object with instance variables Therefore, it is legal to invoke another method within the definition of a constructor, since it has the newly created object as its calling object – For example, mutator methods can be used to set the values of the instance variables – It is even possible for one constructor to invoke another 4-16 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Constructor Has a this Parameter Like any ordinary method, every constructor has a this parameter The this parameter can be used explicitly, but is more often understood to be there than written down The first action taken by a constructor is to automatically create an object with instance variables Then within the definition of a constructor, the this parameter refers to the object created by the constructor 4-17 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Include a No-Argument Constructor If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class, Java will not provide this default constructor If you include any constructors in your class, be sure to provide your own no-argument constructor as well 4-18 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Methods A static method is one that can be used without a calling object A static method still belongs to a class, and its definition is given inside the class definition When a static method is defined, the keyword static is placed in the method header public static returnedType myMethod(parameters) {... } Static methods are invoked using the class name in place of a calling object returnedValue = MyClass.myMethod(arguments); 5-19 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Variables A static variable is a variable that belongs to the class as a whole, and not just to one object – There is only one copy of a static variable per class, unlike instance variables where each object has its own copy All objects of the class can read and change a static variable Although a static method cannot access an instance variable, a static method can access a static variable A static variable is declared like an instance variable, with the addition of the modifier static private static int myStaticVariable; 5-20 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Variables A static variable should always be defined private, unless it is also a defined constant – The value of a static defined constant cannot be altered, therefore it is safe to make it public – In addition to static, the declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed public static final int BIRTH_YEAR = 1954; When referring to such a defined constant outside its class, use the name of its class in place of a calling object int year = MyClass.BIRTH_YEAR; 5-21 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory A computer has two forms of memory Secondary memory is used to hold files for "permanent" storage Main memory is used by a computer when it is running a program – Values stored in a program's variables are kept in main memory 5-22 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory Main memory consists of a long list of numbered locations called bytes – Each byte contains eight bits: eight 0 or 1 digits The number that identifies a byte is called its address – A data item can be stored in one (or more) of these bytes – The address of the byte is used to find the data item when needed 5-23 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory Values of most data types require more than one byte of storage – Several adjacent bytes are then used to hold the data item – The entire chunk of memory that holds the data is called its memory location – The address of the first byte of this memory location is used as the address for the data item A computer's main memory can be thought of as a long list of memory locations of varying sizes 5-24 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables in Memory 5-25 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References Every variable is implemented as a location in computer memory When the variable is a primitive type, the value of the variable is stored in the memory location assigned to the variable – Each primitive type always require the same amount of memory to store its values 5-26 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References When the variable is a class type, only the memory address (or reference) where its object is located is stored in the memory location assigned to the variable – The object named by the variable is stored in some other location in memory – Like primitives, the value of a class variable is a fixed size – Unlike primitives, the value of a class variable is a memory address or reference – The object, whose address is stored in the variable, can be of any size 5-27 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References Two reference variables can contain the same reference, and therefore name the same object – The assignment operator sets the reference (memory address) of one class type variable equal to that of another – Any change to the object named by one of theses variables will produce a change to the object named by the other variable, since they are the same object variable2 = variable1; 5-28 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Type Variables Store a Reference (Part 1 of 2) 5-29 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Type Variables Store a Reference (Part 2 of 2) 5-30 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 1 of 3) 5-31 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 2 of 3) 5-32 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 3 of 3) 5-33 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Parameters All parameters in Java are call-by-value parameters – A parameter is a local variable that is set equal to the value of its argument – Therefore, any change to the value of the parameter cannot change the value of its argument Class type parameters appear to behave differently from primitive type parameters – They appear to behave in a way similar to parameters in languages that have the call-by-reference parameter passing mechanism 5-34 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Parameters The value plugged into a class type parameter is a reference (memory address) – Therefore, the parameter becomes another name for the argument – Any change made to the object named by the parameter (i.e., changes made to the values of its instance variables) will be made to the object named by the argument, because they are the same object – Note that, because it still is a call-by-value parameter, any change made to the class type parameter itself (i.e., its address) will not change its argument (the reference or memory address) 5-35 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Parameters of a Class Type 5-36 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Public static void changer(ToyClass aparameter) { aParameter.name =“Hot Shot”; aParameter.number = 42; } The changer method in ToyClass

Memory Picture for Display 5.14 (Part 1 of 3) 5-38 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Memory Picture for Display 5.14 (Part 2 of 3) 5-39 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Memory Picture for Display 5.14 (Part 3 of 3) 5-40 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Differences Between Primitive and Class-Type Parameters A method cannot change the value of a variable of a primitive type that is an argument to the method In contrast, a method can change the values of the instance variables of a class type that is an argument to the method 5-41 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Comparing Parameters of a Class Type and a Primitive Type (Part 1 of 2) 5-42 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Comparing Parameters of a Class Type and a Primitive Type (Part 2 of 2) 5-43 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Toy Class to Use in Display 5.16 (Part 1 of 2) 5-44 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Toy Class to Use in Display 5.16 (Part 2 of 2) 5-45 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructors A copy constructor is a constructor with a single argument of the same type as the class The copy constructor should create an object that is a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object Note how, in the Date copy constructor, the values of all of the primitive type private instance variables are merely copied 5-46 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructor for a Class with Primitive Type Instance Variables public Date(Date aDate) { if (aDate == null) //Not a real date. { System.out.println("Fatal Error."); System.exit(0); } month = aDate.month; day = aDate.day; year = aDate.year; } 5-47 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructor for a Class with Class Type Instance Variables Unlike the Date class, the Person class contains three class type instance variables If the born and died class type instance variables for the new Person object were merely copied, then they would simply rename the born and died variables from the original Person object born = original.born //dangerous died = original.died //dangerous – This would not create an independent copy of the original object 5-48 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Mutable and Immutable Classes A class that contains no methods (other than constructors) that change any of the data in an object of the class is called an immutable class – Objects of such a class are called immutable objects – It is perfectly safe to return a reference to an immutable object because the object cannot be changed in any way – The String class is an immutable class 5-49 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Mutable and Immutable Classes A class that contains public mutator methods or other public methods that can change the data in its objects is called a mutable class, and its objects are called mutable objects – Never write a method that returns a mutable object – Instead, use a copy constructor to return a reference to a completely independent copy of the mutable object 5-50 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Deep Copy Versus Shallow Copy A deep copy of an object is a copy that, with one exception, has no references in common with the original – Exception: References to immutable objects are allowed to be shared Any copy that is not a deep copy is called a shallow copy – This type of copy can cause dangerous privacy leaks in a program 5-51 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exercise: What is the output of the following code? Date date1 = new Date(“January”,1,2006); Date date2; date2 = date1; System.out.println(date2); date2.setDate(“July”,4, 1776); System.out.println(date1); System.out.println(date2); Date date1 = new Date(“January”,1,2006); Date date2; date2 = new Date(date1); System.out.println(date2); date2.setDate(“July”,4, 1776); System.out.println(date1); System.out.println(date2); Code A Code B

The StringTokenizer Class The StringTokenizer class is used to recover the words or tokens in a multi-word String – You can use whitespace characters to separate each token, or you can specify the characters you wish to use as separators – In order to use the StringTokenizer class, be sure to include the following at the start of the file: import java.util.StringTokenizer; 4-53 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the StringTokenizer Class (Part 1 of 2) 4-54 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the StringTokenizer Class (Part 2 of 2) 4-55 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Math Class The Math class provides a number of standard mathematical methods – It is found in the java.lang package, so it does not require an import statement – All of its methods and data are static, therefore they are invoked with the class name Math instead of a calling object – The Math class has two predefined constants, E ( e, the base of the natural logarithm system) and PI ( , ) area = Math.PI * radius * radius; 5-56 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 1 of 5) 5-57 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 2 of 5) 5-58 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 3 of 5) 5-59 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 4 of 5) 5-60 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 5 of 5) 5-61 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Announcement: Programming assignment 1: – Page 92: project 9. Page 160: project 3. Due date: – Thursday, Feb 14th. Late work may be submitted on Friday or Saturday with 5% penalty per day. No work will be accepted after Saturday. How to turn in: – your files (both.java &.class files) to TA and me with “cs102 assignment1” in your message subject line. Grading. – Correctness: 80 points. – Readability: 20 points.