Writing Classes - PowerPoint PPT Presentation

1 / 12
About This Presentation
Title:

Writing Classes

Description:

import the class or the package containing the class. declare a variable of that type (you don't do this for Math or JOptionPane) ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 13
Provided by: foxr
Category:
Tags: classes | don | writing

less

Transcript and Presenter's Notes

Title: Writing Classes


1
Writing Classes
  • You have already used classes
  • String, Random, Graphics, JOptionPane, Math, etc
  • To use a class
  • import the class or the package containing the
    class
  • declare a variable of that type (you dont do
    this for Math or JOptionPane)
  • instantiate the variable using new, as in Random
    g new Random( )
  • interact with the variable (called an object) by
    passing messages
  • We now turn to developing our own classes
  • One aspect of OOP is that any new class expands
    the language
  • you may use your own classes or others classes
    in building new classes
  • thus, the language continues to grow
  • Another use of the class is for modeling the
    real-world closer
  • a class represents a class of object in the world
    that we might want to interact with
  • each class is self-contained

2
Example Die Class
// import Die -- in JCreator, dont import your
own // classes, just leave them in the same
directory as // this class public class
DiceStats public static void main(String
args) Die die1, die2 int i,
roll die1 new Die(6) die2 new
Die(6) for(i0ilt50i)
die1.rollDie( )
die2.rollDie( ) roll
die1.getValue( ) die2.getValue( )
System.out.println("Roll is "
roll)
import java.util.Random public class Die
private int numSides private int value
private Random generator public
Die(int size) // constructor
value 0 generator new Random(
) numSides size public int
getValue() // used to return return
value // the dies value public
void rollDie() value
Math.abs(generator.nextInt( )) numSides 1
// assume this file is called
Die.java
3
Writing and Using Classes
class named Foo Class Variables d1 d2 Methods m1
m2 m3
Program that uses the class Foo Foo o new
Foo( ) o.m1( ) o.m2( ) // cannot directly
access // o.d1 or o.d2
Define a class by supplying methods and data
instances Methods are pieces of code
(like functions or procedures) Class Variables
are variables known only inside the class and
describe this particular instance
You (or others) write programs that
create instances (objects) of the Class that you
defined Now, they use and manipulate the objects
through Message passing
4
Defining a Class
  • In essence, defining a class is like defining our
    programs that we created previously with a main
    method except now
  • we will not use the word static
  • there will be class variables
  • there will be no main method
  • there will be other methods, including a
    constructor method
  • the constructor is invoked when the object is
    first instantiated with new
  • the purpose of a constructor is to initialize
    some or all of the data instances
  • like our previous programs, a class is stored in
    a file of the same name
  • if the class is Foo, it is stored in the file
    Foo.java
  • we will have to use public and private visibility
    modifiers when we define our methosd and data
    instances
  • Before writing your class, you should consider
  • what data does it need?
  • what methods are required
  • which of the methods should be available to other
    programs? are any of the methods used only
    internally?

5
Some Observations
  • We could have made the Die class differently
  • since generator is only referenced in rollDie, it
    could have been a local variable instead of an
    instance data
  • but if we had done this, because of how Random
    works, we might have always generated the same
    die roll!
  • rollDie could have returned the new value
  • so that we would not need getValue, or at least
    so that we could have cut down on the statements
    in the DieStats class
  • we could also provide a second constructor that
    receives no parameter
  • such a Die would default to a 6-sided Die

public Die( ) numSides 6
value 0 generator new Random( )
Having 2 constructors overloads the
constructor just as we could overload other
methods
6
Public, Private and Protected
  • These are visibility modifiers
  • should a class item be accessible outside of the
    class?
  • if public, then the item can be used directly by
    anyone
  • if private, then the item can only be referenced
    inside the class
  • if protected, then the item can only be
    referenced inside the class, or by classes inside
    the same package (file) or by those child classes
    created using the extends reserved word (recall
    extends JPanel)
  • usually class variables will only be private
  • methods will usually be public unless they are
    only used by methods of the given class in which
    case they should be private
  • there are occasions for having private methods
    but there are no reason for having public
    instance data
  • if your class has constants, they are usually
    public though since no one can change them no
    matter what (since they are constants)

7
Example Date Class
  • The Date class will store a Dates information
  • month
  • date
  • year
  • all will be int values as in 6 / 22 / 2004
  • what constructors should it have?
  • lets provide one that receives the three values
    as int parameters, one that receives no values
    (we will then set the date to today, assuming
    today is 6/22/2004) and one that receives the
    date as a String written as //

public class Date public Date(int a, int b,
int c) private int month, date,
year month a date b year c
public Date( ) public
Date(String x) month 6 date
22 year 2004 // see next slide
8
Date Class Continued
public void advanceDate( ) date
if(date gt 28 month 2)
month date 1 else if
(date gt 30 month 4 month 6
month 9 month 11)
month date 1 else if
(date gt 31) month date 1 if
(month 13) month 1 year

public Date(String x) String s1
x.substring(0, 2) String s2
x.substring(3, 2) String s3
x.substring(6, 2) month
Integer.parseInt(s1) date
Integer.parseInt(s2) year 2000
Integer.parseInt(s3) public void
setDate(int newMonth, int newDate, int newYear)
month newMonth date
newDate year newYear public
void getDate( ) System.out.println(mo
nth "/" date "/20" year)
9
Class Methods Mutators, Accessors, Constructors
  • We have already mentioned Constructors
  • methods that initialize an object
  • all classes must have at least a constructor
    (although if you forget to provide one, Java
    gives you a default constructor that doesnt do
    much)
  • In addition, a class will require methods to
  • access a data member to return the value so that
    it can be used elsewhere (known as accessor
    methods)
  • allow values stored in data members to be
    updated/altered (known as mutator methods)
  • in the Date example, setDate and advanceDate are
    mutators, and getDate is an accessor

10
The toString( ) Method
  • Imagine if you created an object of type Date, d
    and then you did
  • System.out.println(d)
  • What would you get?
  • d is not really a Date, it is called a pointer
    to a Date, where a pointer is the address in
    memory where the Date happens to be stored
  • outputing d will usually just output the address,
    which looks like garbage to us
  • If, however, you create a method in your class
    called toString, then System.out.println(d) will
    invoke that method
  • this method should return a String, which is then
    used by System.out.println to output the given
    object

public String toString( ) return
month / date / year
11
Programming Process with Classes
  • If you write a class that you plan to use in
    another class, you must first compile the class
    to be used
  • this class will not have a main method, so it can
    not be run directly
  • Once compiled, you use it in another class (much
    as you have used String or Random)
  • declare a variable to be of the class type (e.g.,
    Die d1)
  • instantiate the variable (e.g., d1 new Die(8))
  • pass the variable messages (d1.rollDie( ))
  • NOTE in JCreator, the compiled class must be in
    the same directory as the class that will use it,
    otherwise you will have to use an import
    statement
  • for simplicity, we will just make sure all of our
    classes are in the same directory
  • You must make sure that your class did compile
    (no syntax errors) before you can try to test it
    out dont just assume it compiled
  • unfortunately, testing the compiled class means
    writing a second user class to test it from
    this can be awkward when it comes to debugging
    complex code

12
this and new
  • The reserved word new plays the role of
    instantiating an object
  • causes the operating system to provide the memory
    space needed for the object
  • initializes the object as needed
  • by calling upon the class constructor method
  • Once done, you now interact with the object
  • if you try to pass a message to an object that is
    declared but not instantiated, you receive a
    NullPointerException
  • this is a reference to this object
  • We can use this if code inside the object must
    refer to the object itself
  • The simplest example occurs in a constructor
    where we want to reference this objects instance
    data rather than a parameter

public class ThisExample private int
x public ThisExample(int x)
this.x x // rest of class defined
here
Write a Comment
User Comments (0)
About PowerShow.com