16
Writing Classes You have already used classes String, Random, Scanner, Math, Graphics, etc To use a class: import the class or the package containing the class create a variable of that type (you don’t have to do this for Math) instantiate the variable using new interact with it 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

Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Embed Size (px)

Citation preview

Page 1: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Writing Classes• You have already used classes

– String, Random, Scanner, Math, Graphics, etc– To use a class:

• import the class or the package containing the class• create a variable of that type (you don’t have to do this for Math)• instantiate the variable using new• interact with it 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

Page 2: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Writing and Using Classesclass named FooData instances:

d1d2d3

Methods:m1m2m3m4

Program that uses the class Foo

Foo o = new Foo( );…

o.m1( );o.m2( );

You (or others) write a program that uses the Class by creating one or more instances of the Class as individual objects. These instances are used by passing them messages, the messages are the names of the object’s methods, and those methods manipulate the object’s data

You define the a Class as:methods (chunks of codeactivated by messages) andinternal data (data instances)that describe the object

Page 3: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Defining a Class• Before now, we just used pre-defined classes, now we

will define our own classes– They will have methods and instance data– They will NOT have a main method– They will have one or more constructor methods

• this method is invoked when the object is first instantiated with “new” so any initial things that the object should have or do are performed in this method

– 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

– 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?

Page 4: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Example: Die Classimport 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 die’s value public void rollDie() { value = Math.abs(generator.nextInt( ))

% numSides + 1; } } // assume this file is called Die.java

// import Die; -- in JCreator, don’t import your own// classes, just leave them in the same directory as// this classpublic class DiceStats{ public static void main(String[] args) {

Die die1, die2;int i, roll;

die1 = new Die(6);die2 = new Die(6);

for(i=0;i<50;i++){

die1.rollDie( ); die2.rollDie( );

roll = die1.getValue( ) + die2.getValue( );

System.out.println("Roll is " + roll);}

}}

Page 5: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

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 constructorsoverloads the constructorjust as we could overloadother methods

Page 6: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

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)

Page 7: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

The static Modifier• static can be applied to a method or variable is static

– It determines whether the item (method/variable) is shared among all objects of the class or if it is specific to an object• For instance, in our Die class, if we have two Die, d1 and d2, they both

have their own instance data value• If we had made value static, then both d1 and d2 would share value and

so if we did d1.rollDie( ) it would affect d2

– We generally do not make instance data static, but we could make methods static• This is the case in a class like Math or JOptionPane• In such a situation, you pass your message directly to the class by name,

not to an object – so we do Math.abs(…) or JOptionPane.showInputDialog(…)

Page 8: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Example: Date Class• The Date class will store a Date’s information:

– Month– Date– Year

• All will be int values as in 6 / 22 / 2004– What constructors should it have?

• Let’s 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 }

Page 9: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Date Class Continued public Date(String x) { String s1 = x.substring(0, 2); String s2 = x.substring(3, 5); String s3 = x.substring(6, 8); 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(month + "/" + date + "/" + year); }

public void advanceDate( ) { date++; if(date > 28 && month = = 2) { month++; date = 1; } else if (date > 30 && month = = 4 | |

month = = 6 | | month = = 9 | |month = = 11)

{month++; date = 1;

} else if (date > 31) {

month++; date = 1; if (month = = 13){ month = 1; year++;}

}}

Page 10: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

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 doesn’t 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

Page 11: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

BaseballPlayer Class Code

public class BaseballPlayer { private String name, position, team; private int atBats, hits, doubles, triples, homers; private double battingAvg, sluggingPct;

public BaseballPlayer(String n) {

name=n;position=null; team=null;atBats=0; hits=0; doubles=0; triples=0;homers=0;

}

public BaseballPlayer(String n, String p, String t) {

name=n;position=p;team=t;atBats=0; hits=0; doubles=0; triples=0;homers=0;

}

public void playsGame(int a, int s, int d, int t, int h) { atBats+=a; hits+=s; doubles+=d; triples+=t; homers+=h; update( );}

public void oneBat(int result) { atBats++; switch(result) {

case 1 : hits++; break;case 2 : doubles++; break;case 3 : triples++; break;case 4 : homers++; break;

} update( );}

public void update( ) { battingAvg=(double)(hits+doubles+triples+

homers)/atBats; sluggingPct=(double)(hits+doubles*2+

triples*3+homers*4)/atBats;}

Page 12: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

Baseball Player Code Continuedpublic double getAvg( ){ return battingAvg;}

public double getSlugging( ) { return sluggingPct; }

public void traded(String newTeam){ team=newTeam;}

public String toString( ){ return name + “\n” + position + “\n”

+ team + “\n” + “bats: ” + battingAvg;}

public class BaseballGame { public static void main(String[ ] args) {

BaseballPlayer b1, b2, b3;b1=new BaseballPlayer(…);b2=new BaseballPlayer(…);b3=new BaseballPlayer(…);b1.playsGame(5, 2, 1, 0, 0);b2.playsGame(4, 3, 0, 0, 0);b3.oneBat(4);b3.oneBat(2);System.out.println(b3);b3.traded(“Cardinals”);b2.traded(“Reds”);System.out.println(b2);System.out.println(b1.getAvg( ));

}}

Page 13: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

The toString( ) Method• What is the toString method? Imagine that we

did not have one and we did– System.out.println(b1);

• What would you get? – All objects are stored in memory and pointed to by things

called reference variables, or pointers– If you try to print out a reference variable, you get the value of

the address in memory of the actual object, not the object’s value(s)

• The role of toString is to provide the programmer with a way to return a String that describes the contents of an object so that it can be printed out– Its up to us as programmers to decide what to print

out in the toString, for the BaseballPlayer, we did not print out all of the information, but we could have

Page 14: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

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 – don’t 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

Page 15: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

What Does new Do?• The reserved word new plays the role of

instantiating an object– This causes the operating system to provide the

memory space needed for the object– And initializes the object as needed

• Many classes require parameters to initialize their object, we will see some examples as we go through this section

• Once done, you can now interact with the object by passing the object messages– However, if you try to pass a message to an object that

is declared but not instantiated, you will receive a NullPointerException

Page 16: Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing

The this Reference• 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 object’s instance data rather than a parameter

public class ThisExample { private int x; private int y;

public ThisExample(int x, int y) { this.x = x;

this.y = y; } … // rest of class defined here}

By using this.x, the Java compiler knows that the left-hand variable is the instance data x in the class and the right-hand variable is the parameter

We will use the this reference when we want to refer to this object as handling some kind of activity like being an Event handler (something you will see later this week)