Creating Objects: Constructors - PowerPoint PPT Presentation

About This Presentation
Title:

Creating Objects: Constructors

Description:

Each resource is uniquely identified by its URL (Universal Resource Locator) ... Class URL provided by Java to model URLs. The constructor for the URL class ... – PowerPoint PPT presentation

Number of Views:14
Avg rating:3.0/5.0
Slides: 26
Provided by: DonSl1
Category:

less

Transcript and Presenter's Notes

Title: Creating Objects: Constructors


1
Creating Objects Constructors
  • Constructor class method(s) used to create an
    object
  • Every class has one or more
  • Name of a constructor method is always the same
    as the name of the class
  • Constructors may or may not have arguments
  • Use the keyword new to create an object
  • Creation of a new object is an operation
  • Keywords (such as new) or symbols that perform
    operations are called operators

2
Constructing a String object
  • The new operation returns a reference to a new
    String object
  • Need a reference variable to receive the result
    of the operation
  • String name
  • name new String(Horace)
  • or
  • String name new String(Horace)

Reference variable
constructor
operator
argument
3
Reading Interactive Data
  • We can use javax.swing package and JOptionPane
    class
  • JOptionPane class has a method call
    showInputDialog that takes a string (as prompt)
    and allows the user to enter a string
  • Eg s1 JOptionPane.showInputDialog("Enter an
    integer")
  • S1 is a string that can now be used.

4
Reading Interactive Data - an example
  • import javax.swing.JOptionPane
  • public class Example1
  • public static void main(String
    args)
  • String s1, s2
  • int n1, n2, max
  • // prompt for integers
  • s1 JOptionPane.showInputDia
    log("Enter an integer")
  • s2 JOptionPane.showInputDia
    log("Enter another integer")
  • // convert these strings to
    integers
  • n1 Integer.parseInt(s1)
  • n2 Integer.parseInt(s2)
  • // find the maximum
  • max Math.max(n1,n2)
  • // print the message and the
    max value
  • JOptionPane.showMessageDialog
    (null, "The biggest is " max)

5
Disk Files
  • Advantages
  • Persistence data in a file lasts longer than
    data on the monitor
  • Capacity more information can be stored on a
    disk than displayed at one time on a monitor
  • Attributes
  • Contents (data)
  • A file name
  • Operations
  • Writing to a file (creating and storing data for
    the first time)
  • Deleting a file
  • Renaming a file
  • Overwriting a file
  • Obtaining contents of a file

6
Modeling disk files
  • Java provides a predefined class to model disk
    files, called File
  • Constructor for the file class
  • Accepts the files name (a String reference) as
    the argument
  • Example
  • File f1 new File(myData.txt)
  • IMPORTANT
  • We have created a reference to a file object
  • This does not create a file on the disk
  • If this file is not on the disk, we cannot do
    anything with this object

7
If the file is on the disk
  • The File object provides two methods that model
    some of the operations we listed earlier
  • delete()
  • File f new File(junk.txt)
  • f.delete()
  • renameTo()
  • File f1, f2
  • f1 new File(junk.txt)
  • f2 new File(garbage.txt)
  • f1.renameTo(f2)
  • Download FileStuff.zip demo

8
Writing output to disk
  • To create a new file, or overwrite an existing
    file, we need a pathway, or stream
  • Java has a predefined class to model this stream,
    FileOutputStream
  • The constructor for FileOutputStream uses a
    reference to a File object as its argument
  • File f new File(stuff.txt)
  • FileOutputStream fstream new
    fileOutputStream(f)
  • Opens the file so that it can receive data
  • Creates a new file if the file does not exist
  • However, it does not provide any convenient
    methods for output

9
Using PrintStream methods for disk files
  • We want a PrintStream object to be associated
    with a disk file and not a monitor
  • The PrintStream constructor takes a reference to
    a FileOutputStream as its argument
  • The PrintStream object is associated with the
    FileOutPutStream
  • Using println() and print() methods on this
    PrintStream object means that output will go to
    the disk file
  • File f new File(stuff.txt)
  • FileOutputStream fstream new
    FileOutputStream(f)
  • PrintStream target new PrintStream(fstream)
  • target.println(This is a new disk file.)

10
Catching exceptions (first pass)
  • In Karel we had runtime errors that would halt
    program flow
  • Try to pick a beeper when none were there
  • To to move through a wall that was in the way
  • A similar type of problem may be trying to access
    a file that is unavailable
  • We will add the line throws Exception to the
    heading of the main() method of our program class
  • public static void main(String args) throws
    Exception

11
Throwing exceptions and methods
  • Any method that can throw an exception must
    acknowledge it in the header with a throws clause
  • A throws clause consists of the keyword throws
    and a list of all Exceptions thrown in the method
  • Example
  • public static void main(String args) throws
    Exception

12
Throwing Exceptions
  • To handle the unexpected, Java uses the throw
    statement
  • throw reference
  • Reference is an object of a subclass of the class
    Exception
  • See the API and the Java Interlude on page ??? of
    the text
  • The throw statement usually takes the following
    form
  • throw new Exception-class(String-argument)
  • This is called throwing an exception

13
Handling the unexpected
  • By default the throws statement launches a chain
    of method terminations from the method that
    executes the throw to the main() method,
    terminating the program itself
  • Often the program can respond to the unexpected
    and recover, by catching the Exception
  • Breaking the cascade of method throwing along the
    invocation chain

14
try catch()
  • To catch an Exception, the statements containing
    invocations of Exception-throwing methods are
    surrounded by braces and preceded with the
    keyword try
  • try
  • someObject.someMethod()
  • Following is the keyword catch and a declaration
    of an reference variable that will refer to the
    thrown Exception object in parentheses
  • catch (Exception e) statements
  • Finally comes a group of statements surrounded by
    braces that will be executed when the Exception
    reaches this method

15
Implementing a trycatch in file output
  • We could also implement the trycatch mechanism
    in the following way
  • File f new File("stuff.txt")
  • try
  • FileOutputStream fstream new
    FileOutputStream(f)
  • PrintStream target new PrintStream(fstream)
  • target.println("This is a new disk file.")
  • catch (FileNotFoundException e)
  • System.out.println("File not found.")
  • We will not worry about the details of this
    implementation at this time

16
Creating or Overwriting a File Summary
  1. Create a File object to represent the file
  2. Create a FileOutputStream object to represent the
    pathway to the file (using the File reference as
    an argument)
  3. Create a PrintStream object to provide a
    convenient output pathway to the file (using the
    FileOutputStream reference as an argument)
  4. Use print() or println() methods of PrintStream
    as needed
  5. Be sure to watch for exceptions appropriately

17
Input from keyboard, file, or network connection
  • Sequence of steps similar to output
  • Construct an object that models some sort of
    input stream
  • FileInputStream
  • BufferedInputStream
  • Use the input stream object to construct an
    InputStreamReader object
  • Models stream of input as a stream of characters
  • Does not recognize boundaries between Strings in
    the input
  • Use the InputStreamReader object to construct a
    BufferedReader object
  • Provides method readLine() reads an entire line,
    creates a String object, and returns a reference
    to that object

18
Input the keyboard
  • Java provides a predefined BufferedInputStream
    object to represent a stream of input that comes
    from the keyboard, System.in
  • Unlike System.out, System.in cannot be used right
    away (different classes)
  • System.in must be used to construct an
    InputStreamReader object
  • Which is used as an argument to construct a
    BufferedReader object
  • Which can then be sent readLine() messages to
    read lines as Strings

19
Getting a line from the keyboard
  • InputStreamReader isr
  • BufferedReader keyBoard
  • String inputLine
  • isr new InputStreamReader(System.in)
  • keyBoard new BufferedReader(isr)
  • inputLine keyBoard.readLine()
  • System.out.print(inputLine)
  • System.out.println("s")

20
Interactive Input/Output
  • A program that expects input from a keyboard,
    must provide that information to the user as it
    runs
  • A general form for interactive input and output
  • System.out.print(prompt goes here)
  • string reference variable keyboard.readLine()
  • possibly compute something
  • System.out.println(output string goes here)

21
Input Disk Files
  • Only slightly more involved that obtaining input
    from a keyboard
  • Instead of BufferedInputStream object
    (System.in), we need a FileInputStream object
  • Construct a FileInputStream object the same as
    constructing a FileOutputStream object
  • File f new File(myData.txt)
  • FileInputStream fs new FileInputStream(f)
  • Now we can use the FileInputStream object as we
    used System.in in getting data from the keyboard

22
Getting a line from a disk file
  • File f new File(myData.txt)
  • FileInputStream fs new FileInputStream(f)
  • InputStreamReader isr
  • BufferedReader input
  • isr new InputStreamReader(fs)
  • input new BufferedReader(isr)
  • String inputLine
  • inputLine input.readLine()
  • System.out.println(inputLine)

23
Network Computing
  • Network concepts
  • Computer network group of computers that can
    directly exchange information with each other
  • Internet a computer network of networks. Allows
    computers on one network to exchange information
    with another computer on a different network
  • THE Internet
  • Each computer has its own unique Internet
    address
  • Internet addresses on the Net are Strings
  • Information on the Net is organized into units
    called network resources (usually a file of some
    type)
  • Each resource is uniquely identified by its URL
    (Universal Resource Locator)
  • Form of URL protocol//internet address/file name

24
Network Input
  • Reading input from the World Wide Web is as
    simple as reading data from a disk file
  • Obtain an InputStream that models a stream of
    input from a Web site
  • Class URL provided by Java to model URLs
  • The constructor for the URL class takes a String
    argument
  • URL u new URL(http//www.whitehouse.gov)
  • It also provides a method, openStream, that takes
    no arguments, but returns an InputStream
  • InputStream ins u.openStream()

25
openStream()
  • Does a lot of work behind the scenes
  • Sets up communication software on your machine
  • Contacts the remote machine
  • Waits for response
  • Sets up connection
  • Constructs an InputStream object to model the
    connection
  • Returns a reference to this object
  • We then construct a BufferedReader as we did for
    disk files and keyboards
  • Download WHWWW.zip demo
Write a Comment
User Comments (0)
About PowerShow.com