3. Using Classes And Objects Based on Java Software Development, 5 th Ed. By Lewis &Loftus.

Slides:



Advertisements
Similar presentations
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Advertisements

Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Aalborg Media Lab 17-Jun-15 Software Design Lecture 4 “ Using Classes & Objects”
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
1 A Sorting Example (a start for Lab 4 problem number 3)
Chapter Day 6. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 DUE Problem set 2 posted 
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Static Class Members Wrapper Classes Autoboxing Unboxing.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class.
Using Classes and Objects Chapters 3 Section 3.3 Packages Section 3.4 Random Class Section 3.5 Math Class Section 3.7 Enumerated Types Instructor: Scott.
Class Library, Formatting, Wrapper Classes, and JUnit Testing
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 DUE right now Assignment 2 Posted – Due Feb 5 prior to class Using Classes and Objects.
Chapter 2: Objects and Primitive Data Classes and Objects String, Random, Math, NumberFormat, DecimalFormat and Wrapper Classes.
Chapter 3 Using Classes and Objects. Chapter Scope Creating objects Services of the String class The Java API class library The Random and Math classes.
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
© 2007 Pearson Addison-Wesley. All rights reserved3-1 Using Classes and Objects We can create more interesting programs using predefined classes and related.
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSE 1201 Object Oriented Programming Using Classes and Objects.
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Using Classes and Objects (Chapter 3) Copyright © 2012 Pearson Education, Inc.
1 Chap. 3 Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L, 3.1 – 3.6.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
1 Wrapper Classes  Sometimes we want to use a primitive type as an object, so there are wrapper classes that will help us.  In particular, we need to.
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Collaboration Policy Programming Tests are individual work. You may not work with others in the class.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
3-1 Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference.
Programming in Java (COP 2250) Lecture 7 Chengyong Yang Fall, 2005.
ELC 312 Day 4. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Agenda Questions? Problem set one due Problem set two Posted in WebCT  Due Sept.
Chapter 3 Using Classes and Objects. 2 We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: If statements.
Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong.
1 CMPT 126 Java Basics Using Classes and Objects.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
1 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Variables in Java A variable holds either
Formatting Output & Enumerated Types & Wrapper Classes
Outline Creating Objects The String Class Packages Formatting Output
Using Classes and Objects
Using Classes and Objects (Chapter 3)
Classes, Libraries & Packages
Chapter 3: Using Classes and Objects
Chapter 3, cont Sept 20, 2004.
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference.
Packages & Random and Math Classes
Outline Creating Objects The String Class The Random and Math Classes
Presentation transcript:

3. Using Classes And Objects Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Creating Objects A variable can have value of A variable can have value of Primitive type—e.g., int count; Primitive type—e.g., int count; Reference to an object—e.g. String city; Reference to an object—e.g. String city; A reference value is an address of memory location. A reference value is an address of memory location. The declaration above does not yet create an object. The declaration above does not yet create an object.

Creating Objects (cont.) To create an object of class String: String city = new String(“Hilo”) To create an object of class String: String city = new String(“Hilo”)  Instantiation—creating an object of a particular class Key word Special method—called Constructor to create a new object

Invoking Methods Class String has dozens of methods defined—indexOf(), substring(), trim(), length(), etc. String name = new String(“San Jose”); int count = name.length(); Class String has dozens of methods defined—indexOf(), substring(), trim(), length(), etc. String name = new String(“San Jose”); int count = name.length(); Invoking object name to execute its method length(), returning the number of characters in the object. Invoking object name to execute its method length(), returning the number of characters in the object. Java Standard Class Library (API) Java Standard Class Library (API)Standard Class Library Standard Class Library

6 References Note that a primitive variable contains the value itself, but an object variable contains the address of the object Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a graphically Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" String name int num 38

7 Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable The act of assignment takes a copy of a value and stores it in a variable For primitive types: For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:

8 Reference Assignment For object references, assignment copies the address: For object references, assignment copies the address: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" "Steve Wozniak"

Aliases Aliases—two or more references that refer to the same object String me, you; me = new String(“Tom Jones”); you = me; // you now points to // same object you = “Patty Duke”; // now, you and me both // point to “Patty Duk” Aliases—two or more references that refer to the same object String me, you; me = new String(“Tom Jones”); you = me; // you now points to // same object you = “Patty Duke”; // now, you and me both // point to “Patty Duk”

Garbage Collection String a = new String (“Alice”); String b = new String (“Beth”); a = b; // a & b point to “Beth” String a = new String (“Alice”); String b = new String (“Beth”); a = b; // a & b point to “Beth” Object that a pointed to originally, “Alice”, has lost its handle and is no longer accessible. Object that a pointed to originally, “Alice”, has lost its handle and is no longer accessible. Such memory is called “garbage.” Such memory is called “garbage.” Java performs automatic garbage collection. Java performs automatic garbage collection. Other languages, e.g., C++, require the programmer to code garbage collection Other languages, e.g., C++, require the programmer to code garbage collection

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

String Class Class String is used so often that Java allows short cut. Given: String s: Class String is used so often that Java allows short cut. Given: String s: s = “Some string literal”; in place of s = “Some string literal”; in place of s = new String(“Some string literal”); s = new String(“Some string literal”); This is allowed only for String. This is allowed only for String.

String Method indexOf(char ch) indexOf(char ch) returns the position of the first occurrence of character ch in a String object Kaimuki, Honolulu, HI returns the position of the first occurrence of character ch in a String object Kaimuki, Honolulu, HI String place = new String(“Kaimuki, …”); char ch = ‘k’; int pos = place.indexOf(ch); // pos = 5 StringMutation.java StringMutation.java StringMutation.java

Your Turn Problem: Given a name in lastName- comma-space-firstName format, print it in firstName-space-lastName format. Problem: Given a name in lastName- comma-space-firstName format, print it in firstName-space-lastName format. String name = “Chang, Charles”; String name = “Chang, Charles”; Solution Solution posComma  position of ‘,’ posComma  position of ‘,’ posBlank  position of blank posBlank  position of blank Len  length of string Len  length of string

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Class Library Class Library Class Library a collection of classes that we can use when developing programs a collection of classes that we can use when developing programs Java Standard Class Library Java Standard Class Library part of any Java development environment, containing hundreds of useful classes part of any Java development environment, containing hundreds of useful classes not part of the Java language, but always available not part of the Java language, but always available Available at: Available at:

Packages The classes of the Java standard class library are organized into packages The classes of the Java standard class library are organized into packages Some packages in the standard library: Some packages in the standard library: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

Importing Packages // import one class in package import java.util.Scanner; … Scanner sc = new Scanner(); // import one class in package import java.util.Scanner; … Scanner sc = new Scanner(); // import all classes in package Import java.util.* … Random rnd = new Random(); // import all classes in package Import java.util.* … Random rnd = new Random(); // java.language.* is implicitly // imported System.out.println(“Hello.”); // java.language.* is implicitly // imported System.out.println(“Hello.”);

Math Class Math class is in java.language package (which means it is imported implicitly) Math class is in java.language package (which means it is imported implicitly) Math class contains method to find Math class contains method to find Square root Square root Trigonometric relations Trigonometric relations Exponentiation, etc Exponentiation, etc Math class methods are static methods— methods that belong to the class and not to individual objects c = Math.sqrt(a * a + b * b); Math class methods are static methods— methods that belong to the class and not to individual objects c = Math.sqrt(a * a + b * b); RandomNumbers.java RandomNumbers.java RandomNumbers.java Quadratic.java Quadratic.java Quadratic.java Quadratic.java

Static Method Instance method Instance method Method that is associated with each instance (object) of a class Method that is associated with each instance (object) of a class E.g., Dog fido = new Dog(); Dog lassie = new Dog(); fido.bark(“bow”); // barks “bow, bow, …” lassie.bark(“oof””); // barks “oof, oof, …” E.g., Dog fido = new Dog(); Dog lassie = new Dog(); fido.bark(“bow”); // barks “bow, bow, …” lassie.bark(“oof””); // barks “oof, oof, …” Method which belongs the class and not to each object Method which belongs the class and not to each object E.g., Dog.countOf(); // returns of number of instantiations E.g., Dog.countOf(); // returns of number of instantiations

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Formatting Output Package java.text contains Package java.text contains Class NumberFormat, which contains Class NumberFormat, which contains Static method getCurrencyInstance() Static method getCurrencyInstance() Static method getPercentInstance() Static method getPercentInstance() double result = ; NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); System.out.println(fmt1.format(result)); // $0.03 NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.pringln(fmt2.format(result)); // 3%

Formatting Output (cont.) Package java.text also contains Package java.text also contains Class DecimalFormat which can be instantiated in the usual way Class DecimalFormat which can be instantiated in the usual way Purchase.java Purchase.java Purchase.java CircleStats.java CircleStats.java CircleStats.java double result = ; DecimalFormat fmt = new DecimalFormat(“0.##”); System.out.println(“Result: “ + fmt.format(result); // 12.34

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Enumerated Types Enumerated type Enumerated type Allows the programmer to define possible values Allows the programmer to define possible values Promotes understandability of code Promotes understandability of code Restricts possible values for a variable Restricts possible values for a variable E.g. E.g. enum Season (spring, summer, fall, winter); enum TrafficLight (red, orange, green); Season current; TrafficLight light; current = Season.summer; light = TrafficLight.green;

Enumerated Types (cont.) enum Season (spring, summer, fall, winter); enum TrafficLight (red, orange, green); Season current; TrafficLight light; current = Season.summer; light = TrafficLight.green; int pos = current.ordinal(); // pos = 1 String color = light.name(); // color = “green” Enumerated type is like class. Enumerated type is like class. Enumerated type has static methods— ordinal() and name(). Enumerated type has static methods— ordinal() and name(). Icecream.java Icecream.java Icecream.java

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Wrapper Class To make primitive types act like classes: To make primitive types act like classes: Primitive Type Wrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

Wrapper Class (cont.) To create an integer object: Integer age = new Integer(40); To create an integer object: Integer age = new Integer(40); Static method to convert String to Integer: int num; String sNum = “125”; num = Integer.parseInt(sNum); // num = 125 Static method to convert String to Integer: int num; String sNum = “125”; num = Integer.parseInt(sNum); // num = 125 Wrapper classes have some useful constants: In Integer class, MAX_VALUE & MIN_VALUE contain largest and smallest int values Wrapper classes have some useful constants: In Integer class, MAX_VALUE & MIN_VALUE contain largest and smallest int values

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Graphical User Interface (GUI) Classes needed for GUI components found in the following packages Classes needed for GUI components found in the following packages java.awt – original package java.awt – original package javax.swing – more versatile classes javax.swing – more versatile classes Both packages are needed to create GUI- based programs Both packages are needed to create GUI- based programs

Graphical User Interface (GUI) GUI Container GUI Container A component used to contain other components A component used to contain other components Frame Frame A container used to display as a separate window—has title, can resize, can scroll A container used to display as a separate window—has title, can resize, can scroll Panel Panel Cannot itself display—must be contained in a container, e.g., frae Cannot itself display—must be contained in a container, e.g., frae Used to organize other components Used to organize other components

Label, TextField All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt and javax.swing. All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt and javax.swing. For consistency, stay with javax.swing. For consistency, stay with javax.swing. Label Label Used to display text, image, or both, which cannot be edited Used to display text, image, or both, which cannot be edited TextField TextField Used to display text for input or editing Used to display text for input or editing Authority.java Authority.java Authority.java

Nested Panels Panels can be nested within another panel, which can all be inserted into a fram Panels can be nested within another panel, which can all be inserted into a fram import javax.swing.*; … JFrame frame = new JFrame(); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); -- add label, textField, etc, to p1 -- add label, textField, etc, to p2 -- add p1 and p2 to frame import javax.swing.*; … JFrame frame = new JFrame(); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); -- add label, textField, etc, to p1 -- add label, textField, etc, to p2 -- add p1 and p2 to frame NestedPanels.java NestedPanels.java NestedPanels.java

Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

Images JLabel object can contain text, image, or both. JLabel object can contain text, image, or both. import javax.swing.*; … JImageIcon img = new JImageIcon(“mypic.gif”); JLabel aLabel = new JLabel(img); import javax.swing.*; … JImageIcon img = new JImageIcon(“mypic.gif”); JLabel aLabel = new JLabel(img); LabelDemo.java LabelDemo.java LabelDemo.java