oop chapter 3 by jlncrnl
TRANSCRIPT
-
8/11/2019 OOP chapter 3 by JLNCRNL
1/59
Chapter 3Using Classes andObjects
-
8/11/2019 OOP chapter 3 by JLNCRNL
2/59
2004 Pearson Addison-Wesley. All rights reserved 3-2
Using Classes and Objects
We can create more interesting programs usingpredefined classes and related objects
Chapter 3 focuses on:
object creation and object referencesthe String,Character and StringBuilder classand its methodsthe Java standard class librarythe Random and Math classes
formatting outputenumerated typeswrapper classesgraphical components and containerslabels and images
-
8/11/2019 OOP chapter 3 by JLNCRNL
3/59
2004 Pearson Addison-Wesley. All rights reserved 3-3
OutlineCreating Objects
String, Character and StringBuilder
Packages
Formatting Output
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
4/59
2004 Pearson Addison-Wesley. All rights reserved 3-4
Creating Objects
A variable holds either a primitive type or areference to an object
A class name can be used as a type to declare anob ject reference v ar iable
String title;
No object is created with this declaration
An object reference variable holds the address ofan object
The object itself must be created separately
-
8/11/2019 OOP chapter 3 by JLNCRNL
5/59
2004 Pearson Addison-Wesley. All rights reserved 3-5
Creating Objects
Generally, we use the new operator to create anobject
title = new String ("Java Software Solutions");
This calls the String o stru tor which isa special method that sets up the object
Creating an object is calledinstant ia t ion
An object is an ins tance of a particular class
-
8/11/2019 OOP chapter 3 by JLNCRNL
6/59
2004 Pearson Addison-Wesley. All rights reserved 3-6
Invoking Methods
We've seen that once an object has beeninstantiated, we can use the do t operato r to invokeits methods
count = title. length ()
A method may return a value , which can be usedin an assignment or expression
A method invocation can be thought of as askingan object to perform a service
-
8/11/2019 OOP chapter 3 by JLNCRNL
7/59
2004 Pearson Addison-Wesley. All rights reserved 3-7
References
Note that a primitive variable contains the valueitself, but an object variable contains the addressof 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 reference graphically
"Steve Jobs"name1
num1 38
-
8/11/2019 OOP chapter 3 by JLNCRNL
8/59
2004 Pearson Addison-Wesley. All rights reserved 3-8
Assignment Revisited
The act of assignment takes a copy of a value andstores it in a variable
For primitive types:
num1 38num2 96
Before:
num2 = num1;
num1 38
num2 38After:
-
8/11/2019 OOP chapter 3 by JLNCRNL
9/59
2004 Pearson Addison-Wesley. All rights reserved 3-9
Reference Assignment
For object references, assignment copies theaddress:
name2 = name1;
name1
name2
Before:"Steve Jobs"
"Steve Wozniak"
name1
name2After:
"Steve Jobs"
-
8/11/2019 OOP chapter 3 by JLNCRNL
10/59
2004 Pearson Addison-Wesley. All rights reserved 3-10
Aliases
Two or more references that refer to the sameobject are called aliases of each other
That creates an interesting situation: one objectcan be accessed using multiple reference
variables
-
8/11/2019 OOP chapter 3 by JLNCRNL
11/59
2004 Pearson Addison-Wesley. All rights reserved 3-11
Garbage Collection
When an object no longer has any valid referencesto it, it can no longer be accessed by the program
The object is useless, and therefore is calledgarbage
Java performs autom atic garbage co l lect ion periodically, returning an object's memory to thesystem for future use
-
8/11/2019 OOP chapter 3 by JLNCRNL
12/59
2004 Pearson Addison-Wesley. All rights reserved 3-12
OutlineCreating Objects
String,Character and StringBuilder
Packages
Formatting Output
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
13/59
2004 Pearson Addison-Wesley. All rights reserved 3-13
String,Character and StringBuilder
Character is a class whose instances can hold asingle character value.
Strings is a class for working fixed-string data-that is unchanging data composed of multiple
characters. StringBuilder and StringBuffer are Classes for
storing and manipulating changeable datacomposed of multiple characters.
-
8/11/2019 OOP chapter 3 by JLNCRNL
14/59
2004 Pearson Addison-Wesley. All rights reserved 3-14
The Character Class
Commonly used methods of the Character Class
isUpperCase() toUpperCase() isLowerCase()
toLowerCase() isDigit() isLetter()
isLetterOrDigit() isWhiteSpace()
The Chracter class is defined in java.lang
-
8/11/2019 OOP chapter 3 by JLNCRNL
15/59
2004 Pearson Addison-Wesley. All rights reserved 3-15
The Character Classimport java.util.*;
public class TestCharacter { public static void main(String[]args){
char aChar;String aString;Scanner keyboard=new Scanner
(System.in);System.out.println("Enter a character:");aString=keyboard.nextLine();aChar=aString.charAt(0);System.out.println("The character is"+
aChar);
if(Character.isUpperCase(aChar))System.out.println(aChar +"is Upper
case");else
System.out.println(aChar+"is not Upper
case");if(Character.isLowerCase(aChar))
System.out.println(aChar +"is Lowercase");
elseSystem.out.println(aChar+"is not lower
case");
if (Character.isLetterOrDigit(aChar))System.out.println(aChar+"is a letter or a
digit");
elseSystem.out.println(aChar+"is neither a
letter nor a digit");
if (Character.isWhitespace(aChar))System.out.println(aChar+"is
whitespace");else
System.out.println(aChar+"is not awhitespace"); } }
Output:Enter a character: AThe character is A
A is Upper caseA is not lower caseAfter toLOwerCase(), aChar is aAfter UpperCase(), aChar is AA is a letter or a digitA is not a whitespace
-
8/11/2019 OOP chapter 3 by JLNCRNL
16/59
2004 Pearson Addison-Wesley. All rights reserved 3-16
The String Class Java Strings is a class and each created String is a
class object
As an object a String variable name is not a simpledata type- it is a reference, a variable that holds a
memory address.title = "Java Software Solutions
-
8/11/2019 OOP chapter 3 by JLNCRNL
17/59
2004 Pearson Addison-Wesley. All rights reserved 3-17
The String ClassString aGreeting=Hello;
Address 10876, nameaGreeting
aGreeting holds theaddress where Hello is stored.
address 26040
address 32564
String aGreeting=Hello; aGreeting= Bonjour
Address 10876, nameaGreeting
aGreeting holds theaddress where Hello is stored.
address 26040
address 32564
26040
Hello
XXYYZZ23
26040
Hello
XXYYZZ23
-
8/11/2019 OOP chapter 3 by JLNCRNL
18/59
2004 Pearson Addison-Wesley. All rights reserved 3-18
String Methods Once a String object has been created, neither its
value nor its length can be changed
Thus we say that an object of the String class isimmutab le
However, several methods of the String classreturn new String objects that are modifiedversions of the original
-
8/11/2019 OOP chapter 3 by JLNCRNL
19/59
2004 Pearson Addison-Wesley. All rights reserved 3-19
The String Class
Commonly used methods of the String Class
Length() toUpperCase() indexOf()
toLowerCase() charAt() endsWith()
startsWith() replace()
-The Chracter class is defined in java.lang
-
8/11/2019 OOP chapter 3 by JLNCRNL
20/59
2004 Pearson Addison-Wesley. All rights reserved 3-20
String Indexes It is occasionally helpful to refer to a particular
character within a string
This can be done by specifying the character'snumeric index
The indexes begin at zero in each string
In the string "Hello" , the character 'H' is at index0 and the 'o' is at index 4
-
8/11/2019 OOP chapter 3 by JLNCRNL
21/59
2004 Pearson Addison-Wesley. All rights reserved 3-21
StringBuilder Used to improve performance when a strings
contents must change.
Sufficient memory space is allocated toaccommodate the number of Unicode characters
in the strings. Contains a memory block called buffer .
-
8/11/2019 OOP chapter 3 by JLNCRNL
22/59
2004 Pearson Addison-Wesley. All rights reserved
StringBuilderimport javax.swing.*;public class StringBuilderDemo {
public static void main(String[]args){
StringBuilder nameString=new StringBuilder("Barbara");int nameStringCapacity=nameString.capacity();System.out.println("Capacity of name string is"+nameStringCapacity);
StringBuilder addressString=null;addressString=new StringBuilder("6311 Hickory nut grove road");
int addStringCapacity=addressString.capacity();System.out.println("Capacity of address String is:" + addStringCapacity);
nameString.setLength(20);System.out.println( "The name is:"+ nameString+"end");addressString.setLength(20);System.out.println("The address is:"+ addressString);}}
Output:Capacity of name string is 23Capacity of address String is:43The name is: Barbara endThe address is:6311 Hickory nut gro
-
8/11/2019 OOP chapter 3 by JLNCRNL
23/59
2004 Pearson Addison-Wesley. All rights reserved 3-23
OutlineCreating Objects
String,Character and StringBuilder
Packages
Formatting Output
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
24/59
2004 Pearson Addison-Wesley. All rights reserved 3-24
Class Libraries A class l ibrary is a collection of classes that we
can use when developing programs The Java s tand ard class l ibrary is part of any Java
development environment
-
8/11/2019 OOP chapter 3 by JLNCRNL
25/59
2004 Pearson Addison-Wesley. All rights reserved 3-25
Packages The classes of the Java standard class library are
organized into packages
Some of the packages in the standard class library:
Package
java.langjava.appletjava.awt
javax.swingjava.netjava.utiljavax.xml.parsers
Purpose
General supportCreating applets for the webGraphics and graphical user interfaces
Additional graphics capabilitiesNetwork communicationUtilitiesXML document processing
-
8/11/2019 OOP chapter 3 by JLNCRNL
26/59
2004 Pearson Addison-Wesley. All rights reserved 3-26
The Random Class The Random class is part of the java.util
package
It provides methods that generate pseudorandomnumbers
A Random object performs complicatedcalculations based on a seed value to produce astream of seemingly random values
-
8/11/2019 OOP chapter 3 by JLNCRNL
27/59
2004 Pearson Addison-Wesley. All rights reserved 3-27
The Random Classimport java.util.Random;public class RandomNumbers{public static void main (String[] args) {
Random generator = new Random();int num1;float num2;num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);num1 = generator.nextInt(10);System.out.println ("From 0 to 9: " + num1);num1 = generator.nextInt(10) + 1;System.out.println ("From 1 to 10: " + num1);num1 = generator.nextInt(15) +20;System.out.println ("From 20 to 34: " + num1);num1 = generator.nextInt(20) -10 ;System.out.println ("From -10 to 9: " + num1);num2 = generator.nextFloat();System.out.println ("A random float (between 0-1): " + num2);num2 = generator.nextFloat() * 6; // 0.0 to 5.999999num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);}
-
8/11/2019 OOP chapter 3 by JLNCRNL
28/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
29/59
2004 Pearson Addison-Wesley. All rights reserved 3-29
The Math Classpublic class TrigonometricDemo {
public static void main(String[] args) {double degrees = 45.0;double radians =
Math.toRadians(degrees);
System.out.format("The value of pi " + "is%.4f%n",
Math.PI);
System.out.format("The sine of %.1f " +"degrees is %.4f%n",degrees, Math.sin(radians));
System.out.format("The cosine of %.1f " +"degrees is %.4f%n",
degrees, Math.cos(radians));
System.out.format("The tangent of %.1f " +"degrees is %.4f%n",
degrees, Math.tan(radians));
System.out.format("The arcsine of %.4f " +"is %.4f degrees %n",
Math.sin(radians),
Math.toDegrees(Math.asin(Math.sin(radians))));
System.out.format("The arccosine of %.4f "+ "is %.4f degrees %n",
Math.cos(radians),
Math.toDegrees(Math.acos(Math.cos(radians))));
System.out.format("The arctangent of %.4f" + "is %.4f degrees %n",
Math.tan(radians),Math.toDegrees(Math.atan(Math.tan(radians))));
}}
Output:The value of pi is 3.1416The sine of 45.0 degrees is 0.7071The cosine of 45.0 degrees is 0.7071
The tangent of 45.0 degrees is 1.0000The arcsine of 0.7071 is 45.0000 degreesThe arccosine of 0.7071 is 45.0000 degreesThe arctangent of 1.0000 is 45.0000 degrees
-
8/11/2019 OOP chapter 3 by JLNCRNL
30/59
2004 Pearson Addison-Wesley. All rights reserved 3-30
The Date Class SimpleDateFormat to control the date/time display
format.
Use java.util.Calendar to extract year, month, day,hour, minute, and second, or manipulating these field(e.g., 7 days later, 3 weeks earlier).
Use java.text.DateFormat to formata Date (form Date to text) and parse a date string(from text to Date). SimpleDateForamt is a subclass ofDateFormat.
j il d j Si l
-
8/11/2019 OOP chapter 3 by JLNCRNL
31/59
3-31
java.util.Date and java.text.SimpleDateFormatimport java.text.SimpleDateFormat;import java.util.Date;
public class DateTest { public static void main(String[] args) {
Date now = new Date();System.out.println("toString(): " + now);
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at'h:m:s a z");
System.out.println("Format 1: " + dateFormatter.format(now));
dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");System.out.println("Format 2: " + dateFormatter.format(now));
dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");System.out.println("Format 3: " + dateFormatter.format(now));}}
Output:toString(): Sat Sep 25 21:27:01 SGT 2010Format 1: Sat, 10-9-25 at 9:27:1 PM SGTFormat 2: Sat 2010.09.25 at 09:27:01 PM SGTFormat 3: Saturday, September 25, 2010
j il C l d
-
8/11/2019 OOP chapter 3 by JLNCRNL
32/59
3-32
java.util.Calendarimport java.util.Calendar;public class Cal {
public static void main(String[] args) {Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);int month = cal.get(Calendar.MONTH); int day =
cal.get(Calendar.DAY_OF_MONTH);int hour = cal.get(Calendar.HOUR_OF_DAY);int minute = cal.get(Calendar.MINUTE);int second = cal.get(Calendar.SECOND);
System.out.printf("Now is %4d/%02d/%02d%02d:%02d:%02d\n", year, month+1, day, hour, minute, second);
}}Output:Now is 2014/07/21 09:32:43
-
8/11/2019 OOP chapter 3 by JLNCRNL
33/59
2004 Pearson Addison-Wesley. All rights reserved 3-33
OutlineCreating Objects
String,Character and StringBuilder
Packages
Formatting Output
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
34/59
2004 Pearson Addison-Wesley. All rights reserved 3-34
Formatting Output The Java standard class library contains classes
that provide formatting capabilities
The NumberFormat class allows you to formatvalues as currency or percentages
The DecimalFormat class allows you to formatvalues based on a pattern
Both are part of the java.text package
-
8/11/2019 OOP chapter 3 by JLNCRNL
35/59
F tti O t t
-
8/11/2019 OOP chapter 3 by JLNCRNL
36/59
2004 Pearson Addison-Wesley. All rights reserved 3-36
Formatting OutputThe NumberFormat class
import java.util.*;import java.text.NumberFormat;
public class NumFormat{public static void main (String[] args)
{final double TAX_RATE = 0.06; // 6% sales tax
int quantity;double subtotal, tax, totalCost, unitPrice;
Scanner scan = new Scanner (System.in);
NumberFormat fmt1 =NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat fmt2 =
NumberFormat.getPercentInstance();
System.out.print ("Enter the quantity: ");quantity = scan.nextInt();
System.out.print ("Enter the unit price: ");unitPrice = scan.nextDouble();
tax = subtotal * TAX_RATE;totalCost = subtotal + tax;
// Print output with appropriate formattingSystem.out.println ("Subtotal: " +
fmt1.format(subtotal));System.out.println ("Tax: " + fmt1.format(tax) + "
at "+ fmt2.format(TAX_RATE));
System.out.println ("Total: " +fmt1.format(totalCost));
}}
Output:Enter the quantity: 5Enter the unit price: 20Subtotal: $100.00Tax: $6.00 at 6%Total: $106.00
-
8/11/2019 OOP chapter 3 by JLNCRNL
37/59
2004 Pearson Addison-Wesley. All rights reserved 3-37
Formatting Output The DecimalFormat class can be used to format a
floating point value in various ways
For example, you can specify that the numbershould be truncated to three decimal places
The constructor of the DecimalFormat classtakes a string that represents a pattern for theformatted number
-
8/11/2019 OOP chapter 3 by JLNCRNL
38/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
39/59
2004 Pearson Addison-Wesley. All rights reserved 3-39
Using the printf() method System.out.printf() method is used to format
numeric values.
Two types of arguments:
A format string (string of characters)
A list of arguments
A format specifier is a placeholder for numericvalue.
-
8/11/2019 OOP chapter 3 by JLNCRNL
40/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
41/59
2004 Pearson Addison-Wesley. All rights reserved 3-41
OutlineCreating Objects
String,Character and StringBuilder
Packages
Formatting Output
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
42/59
2004 Pearson Addison-Wesley. All rights reserved 3-42
Wrapper Classes The java.lang package contains wrapper
classes that correspond to each primitive type:
Primitive Type Wrapper Class
byte Byte
short Shortint Integer
long Long
float Float
double Double
char Character
boolean Boolean
void Void
-
8/11/2019 OOP chapter 3 by JLNCRNL
43/59
2004 Pearson Addison-Wesley. All rights reserved 3-43
Wrapper Classes The following declaration creates an Integer
object which represents the integer 40 as an object
Integer age = new Integer(40);
An object of a wrapper class can be used in anysituation where a primitive value will not suffice
For example, some objects serve as containers ofother objects
Primitive values could not be stored in suchcontainers, but wrapper objects could be
-
8/11/2019 OOP chapter 3 by JLNCRNL
44/59
2004 Pearson Addison-Wesley. All rights reserved 3-44
Wrapper Classes Wrapper classes also contain static methods that
help manage the associated type
For example, the Integer class contains amethod to convert an integer stored in a String to
an int value:num = Integer.parseInt( str ) ;
The wrapper classes often contain useful
constants as well The Integer class contains MIN_VALUE and
MAX_VALUE which hold the smallest and largestint values
-
8/11/2019 OOP chapter 3 by JLNCRNL
45/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
46/59
2004 Pearson Addison-Wesley. All rights reserved 3-46
OutlineCreating Objects
The String Class
Packages
Formatting Output
Enumerated Types
Wrapper Classes
Components and Containers
Images
-
8/11/2019 OOP chapter 3 by JLNCRNL
47/59
2004 Pearson Addison-Wesley. All rights reserved 3-47
GUI Components A GUI co m p o n en t is an object that represents a
screen element such as:
button text field label
scroll bar menu check box
Allows user to interact with program
GUI-related classes are defined primarily in thejava.awt and the javax.swing packages
The Abst rac t Window ing Too lk i t (AWT) was theoriginal Java GUI package
-
8/11/2019 OOP chapter 3 by JLNCRNL
48/59
2004 Pearson Addison-Wesley. All rights reserved 3-48
GUI Components The Swing package provides additional and more
versatile components
Both packages are needed to create a Java GUI-based program
-
8/11/2019 OOP chapter 3 by JLNCRNL
49/59
2004 Pearson Addison-Wesley. All rights reserved 3-49
GUI Containers A GUI conta iner is a component that is used to
hold and organize other components
A f rame is a container that is used to display aGUI-based Java application
A frame is displayed as a separate window with atitle bar
The frame can be repositioned and resized on the
screen as needed
-
8/11/2019 OOP chapter 3 by JLNCRNL
50/59
2004 Pearson Addison-Wesley. All rights reserved 3-50
GUI Containers A panel is a container that cannot be displayed on
its own but is used to organize other components
A panel must be added to another container to bedisplayed
Frames from JFrame class
Panels from JPanel class
Frame has multiple panels
The visible elements of the interface are displayedin the content pane
-
8/11/2019 OOP chapter 3 by JLNCRNL
51/59
2004 Pearson Addison-Wesley. All rights reserved 3-51
GUI Containers A GUI container can be classified as either
heavyweight or lightweight
A heavyweigh t con ta iner is one that is managed bythe underlying operating system
A l igh tweigh t con ta iner is managed by the Javaprogram itself
Occasionally this distinction is important
A frame is a heavyweight container and a panel isa lightweight container
-
8/11/2019 OOP chapter 3 by JLNCRNL
52/59
2004 Pearson Addison-Wesley. All rights reserved 3-52
Labels A label is a GUI component that displays a line of
text
Labels are usually used to display information oridentify other components in the interface
Let's look at a program that organizes two labelsin a panel and displays that panel in a frame
See Authority.java
This program is not interactive, but the frame canbe repositioned and resized
Labels
http://localhost/var/www/apps/conversion/tmp/examples/chap03/Authority.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap03/Authority.java -
8/11/2019 OOP chapter 3 by JLNCRNL
53/59
2004 Pearson Addison-Wesley. All rights reserved 3-53
Labelsimport java.awt.*;import javax.swing.*;
public class Authority{ public static void main (String[] args) {
JFrame frame = new JFrame ("Authority");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel primary = new JPanel(); primary.setBackground (Color.yellow);primary.setPreferredSize (new Dimension(250, 75));
JLabel label1 = new JLabel (Technological University of the Philippines,"); JLabel label2 = new JLabel (Manila");
primary.add (label1); primary.add (label2);
frame.getContentPane().add(primary);frame.pack();frame.setVisible(true);
}}
-
8/11/2019 OOP chapter 3 by JLNCRNL
54/59
2004 Pearson Addison-Wesley. All rights reserved 3-54
Nested Panels Containers that contain other components make
up the con tainm ent h ierarchy of an interface
This hierarchy can be as intricate as needed tocreate the visual effect desired
The following example nests two panels inside athird panel note the effect this has as the frameis resized
See NestedPanels.java Every container is managed by an object called:
A Layout Manager
http://localhost/var/www/apps/conversion/tmp/examples/chap03/NestedPanels.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap03/NestedPanels.java -
8/11/2019 OOP chapter 3 by JLNCRNL
55/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
56/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
57/59
2004 Pearson Addison-Wesley. All rights reserved 3-57
Images Images are often used in a programs with a
graphical interface
Java can manage images in both JPEG and GIFformats
As we've seen, a JLabel object can be used todisplay a line of text
It can also be used to display an image
That is, a label can be composed of text, andimage, or both at the same time
-
8/11/2019 OOP chapter 3 by JLNCRNL
58/59
-
8/11/2019 OOP chapter 3 by JLNCRNL
59/59
Summary Chapter 3 focused on:
object creation and object referencesthe String , Character and StringBuilder class and itsmethodsthe Java standard class library
the Random and Math classesformatting outputwrapper classesgraphical components and containers
labels and images