oop chapter 4 by jlncrnl

Upload: chiechiekoy

Post on 10-Oct-2015

22 views

Category:

Documents


0 download

DESCRIPTION

writing classes

TRANSCRIPT

  • Chapter 4Writing Classes

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Writing ClassesWe've been using predefined classes. Now we will learn to write our own classes to define objectsChapter 4 focuses on:class definitionsinstance dataencapsulation and Java modifiersmethod declaration and parameter passingconstructorsgraphical objectsevents and listenersbuttons and text fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • ClassesClasses are constructs that define objects of the same type. (Building plan of similar objects) A Java class uses variables to define data fields and methods to define behaviors. A class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

    2004 Pearson Addison-Wesley. All rights reserved

  • An object has unique identitystatebehaviorsState(attributes) consists of a set of data fields (properties) with their current values. Behavior(operations) of an object is defined by a set of methods.

    2004 Pearson Addison-Wesley. All rights reserved

    (A) A generic object

    method 1

    data field m

    method n

    data field 1

    ...

    ...

    State (Properties)

    Behavior

    findArea()

    radius = 5

    (B) An example of circle object

    Data field, State Properties

    Method, Behavior

  • ObjectsAn object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

    2004 Pearson Addison-Wesley. All rights reserved

    Class Name: Student

    Data Fields:

    name is _______

    Methods:

    takeCourse

    Student Object 3

    Data Fields:

    name is Meltem

    Student Object 2

    Data Fields:

    name is Onur

    Student Object 1

    Data Fields:

    name is Kerem

    Three objects of the Student class

    A class template

  • class Planet{public double radius;public String name;public static final long g = 10;public void display(){System.out.println("Radius "+ radius);System.out.println("Name " + name);System.out.println("Long "+ g);}public void initialize(){radius = 10;//usagename = "Dunya";//usage}}class ExPlanet{public static void main(String [] args){Planet p = new Planet(); // creationp. initialize();//usagep.display();//usage}}

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*ClassesA class can contain data declarations and method declarationsData declarationsMethod declarations

    2004 Pearson Addison-Wesley. All rights reserved

  • Classes

    2004 Pearson Addison-Wesley. All rights reserved

    class Circle {

    /** The radius of this circle */

    double radius = 1.0;

    /** Construct a circle object */

    Circle() {

    }

    /** Construct a circle object */

    Circle(double newRadius) {

    radius = newRadius;

    }

    /** Return the area of this circle */

    double getArea() {

    return radius * radius * 3.14159;

    }

    }

    Data field

    Method

    Constructors

  • 2004 Pearson Addison-Wesley. All rights reserved4-*

    2004 Pearson Addison-Wesley. All rights reserved

  • 4-*

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*ClassesWell want to design the Die class with other data and methods to make it a versatile and reusable resourceAny given program will not necessarily use all aspects of a given classSee RollingDice.javaSee Die.java

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*public class Die { private final int MAX = 6; // maximum face value

    private int faceValue; // current value showing on the die

    public Die() { faceValue = 1; }

    public int roll() { faceValue = (int)(Math.random() * MAX)+1; return faceValue; }

    public void setFaceValue (int value) { faceValue = value; }

    public int getFaceValue() { return faceValue; }

    public String toString() { String result = Integer.toString(faceValue);

    return result; }}public class RollingDice{public static void main (String[] args){ Die die1, die2; int sum;

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

    die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

    die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

    sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum);

    sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); } }

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Output:

    Die One: 1, Die Two: 5Die One: 1, Die Two: 4Sum: 5Die One: 1, Die Two: 5New sum: 6

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*public class Die2 { private final int MIN_FACES = 4;

    private int numFaces; // number of sides on the die private int faceValue; // current value showing on the die

    public Die2 () { numFaces = 6; faceValue = 1; }public Die2 (int faces) { if (faces < MIN_FACES) numFaces = 6; else numFaces = faces;

    faceValue = 1; }

    public int roll () { faceValue = (int) (Math.random() * numFaces) + 1; return faceValue; }

    public int getFaceValue () { return faceValue; }}public class SnakeEyes{public static void main (String[] args) { final int ROLLS = 500; int snakeEyes = 0, num1, num2;

    Die2 die1 = new Die2(); // creates a six-sided die Die2 die2 = new Die2(); // creates a twenty-sided die

    for (int roll = 1; roll

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Output: Die 1 4 Die 2 5Die 1 2 Die 2 2Die 1 2 Die 2 1Die 1 2 Die 2 3Die 1 6 Die 2 4Die 1 1 Die 2 2Die 1 1 Die 2 2Die 1 2 Die 2 4Die 1 3 Die 2 3Die 1 6 Die 2 1Die 1 4 Die 2 2Die 1 2 Die 2 2Die 1 5 Die 2 1Die 1 6 Die 2 6Die 1 2 Die 2 1Die 1 2 Die 2 3Die 1 1 Die 2 2Die 1 1 Die 2 6Number of rolls: 200Number of snake eyes: 3Ratio: 0.015

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*The Die ClassThe Die class contains two data valuesa constant MAX that represents the maximum face valuean integer faceValue that represents the current face valueThe roll method uses the random method of the Math class to determine a new face valueThere are also methods to explicitly set and get the current face value at any time

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*The toString MethodAll classes that represent objects should define a toString methodThe toString method returns a character string that represents the object in some wayIt is called automatically when an object is concatenated to a string or when it is passed to the println method

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved

  • ConstructorsCircle() {}

    Circle(double newRadius) { radius = newRadius;}Constructors are a special kind of methods that are invoked to perform initializing actions.

    2004 Pearson Addison-Wesley. All rights reserved

  • Constructors, cont.A constructor with no parameters is referred to as a no-arg constructor. Constructors must have the same name as the class itself. Constructors do not have a return typenot even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

    2004 Pearson Addison-Wesley. All rights reserved

  • class Emp{private String name;private String id;private int salary;Emp() // default constructor. No argument list{name = Ahmet";id = "1234";salary = 100;}public Emp(String n, String i, int s) // non-default constructor{name = n;id = i;salary = s;}void display(){System.out.println("\nEmploye Info ");System.out.println("Name "+ name);System.out.println("ID "+ id);System.out.println("Salary "+ salary);}}

    2004 Pearson Addison-Wesley. All rights reserved

  • class ExEmp{public static void main(String [] args){Emp e1 = new Emp(); e1.display();Emp e4 = new Emp("Ali","98745", 400); e4.display(); }}

    2004 Pearson Addison-Wesley. All rights reserved

  • Creating Objects Using Constructorsnew ClassName();

    Example:new Circle();

    new Circle(5.0);

    2004 Pearson Addison-Wesley. All rights reserved

  • Default ConstructorA class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.

    2004 Pearson Addison-Wesley. All rights reserved

  • public class Student {private String name;private String studentID;private String surname;private Course[] takenCourses;private int state;public Student(String nameParam,String surnameParam) {name=nameParam;surname=surnameParam;}public static void main(String[] args) {Student s1 = new Student(Onur,Saran);}}

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Data ScopeThe scope of data is the area in a program in which that data can be referenced (used)Data declared at the class level can be referenced by all methods in that classData declared within a method can be used only in that methodData declared within a method is called local dataIn the Die class, the variable result is declared inside the toString method -- it is local to that method and cannot be referenced anywhere else

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Instance DataThe faceValue variable in the Die class is called instance data because each instance (object) that is created has its own version of itA class declares the type of the data, but it does not reserve any memory space for itEvery time a Die object is created, a new faceValue variable is created as wellThe objects of a class share the method definitions, but each object has its own data spaceThat's the only way two objects can have different states

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Instance DataWe can depict the two Die objects from the RollingDice program as follows:

    Each object maintains its own faceValue variable, and thus its own state

    2004 Pearson Addison-Wesley. All rights reserved

  • Reference Data FieldsThe data fields can be of reference types. For example, the following Student class contains a data field name of the String type.

    public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000'}

    2004 Pearson Addison-Wesley. All rights reserved

  • Default Value for a Data FieldThe default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); }}

    2004 Pearson Addison-Wesley. All rights reserved

  • Examplepublic class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); }}Compilation error: variables not initializedJava assigns no default value to a local variable inside a method.

    2004 Pearson Addison-Wesley. All rights reserved

  • Differences between Variables of Primitive Data Types and Object Types

    2004 Pearson Addison-Wesley. All rights reserved

    Created using new Circle()

    Object typeCircle c c

    1

    c: Circle

    radius = 1

    Primitive typeint i = 1 i

    reference

  • Copying Variables of Primitive Data Types and Object Types

    2004 Pearson Addison-Wesley. All rights reserved

    Before:

    Primitive type assignment i = j

    i

    1

    2

    j

    2

    j

    2

    After:

    i

    Before:

    Object type assignment c1 = c2

    c1

    c2

    C2: Circle

    radius = 9

    c2

    c1: Circle

    radius = 5

    After:

    c1

    c1: Circle

    radius = 5

    C2: Circle

    radius = 9

  • Instance Variables and Methods

    Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.

    2004 Pearson Addison-Wesley. All rights reserved

  • Static Variables, Constants, and MethodsStatic variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

    2004 Pearson Addison-Wesley. All rights reserved

  • Static Variables, Constants, and Methods, cont.

    2004 Pearson Addison-Wesley. All rights reserved

    radius

    Circle

    radius: double

    numberOfObjects: int

    getNumberOfObjects(): int

    +getArea(): double

    circle2

    radius = 5

    numberOfObjects = 2

    1

    instantiate

    circle1

    radius = 1

    numberOfObjects = 2

    instantiate

    UML Notation:

    underline: static variables or methods

    Memory

    2

    5

    radius

    numberOfObjects

  • 2004 Pearson Addison-Wesley. All rights reserved4-*UML DiagramsUML stands for the Unified Modeling LanguageUML diagrams show relationships among classes and objectsA UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods)Lines between classes represent associationsA dotted arrow shows that one class uses the other (calls its methods)

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*UML Class DiagramsA UML class diagram for the RollingDice program:

    2004 Pearson Addison-Wesley. All rights reserved

  • UML Class Diagram(Unified Modeling Languauge)

    2004 Pearson Addison-Wesley. All rights reserved

    Circle

    radius: double

    Circle()

    Circle(newRadius: double)

    getArea(): double

    UML notation for objects

    UML Class Diagram

    circle1: Circle

    radius: 10

    circle2: Circle

    radius: 25

    Constructors and Methods

    Data fields

    circle3: Circle

    radius: 125

    Class name

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*EncapsulationEncapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*EncapsulationAn encapsulated object can be thought of as a black box -- its inner workings are hidden from the clientThe client invokes the interface methods of the object, which manages the instance data

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; }} public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()); }}

    ExampleOutput:

    Name : James Age : 20

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Benefits of Encapsulation:

    1. The fields of a class can be made read-only or write-only.

    2. A class can have total control over what is stored in its fields.

    3. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Visibility ModifiersIn Java, we accomplish encapsulation through the appropriate use of visibility modifiersA modifier is a Java reserved word that specifies particular characteristics of a method or dataWe've used the final modifier to define constantsJava has three visibility modifiers: publicprotected private

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Visibility ModifiersProvide servicesto clientsSupport othermethods in theclassEnforceencapsulationViolateencapsulation

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Accessors and MutatorsBecause instance data is private, a class usually provides services to access and modify data valuesAn accessor method returns the value of a variableA mutator method changes the value of a variableThe names of accessor and mutator methods take the form getX and setX, respectively, where X is the name of the valueThey are sometimes called getters and setters

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Mutator RestrictionsThe use of mutators gives the class designer the ability to restrict a clients options to modify an objects stateA mutator is often designed so that the values of variables can be set only within particular limitsFor example, the setFaceValue mutator of the Die class should have restricted the value to the valid range (1 to MAX)

    2004 Pearson Addison-Wesley. All rights reserved

  • The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.

    2004 Pearson Addison-Wesley. All rights reserved

    public class C2 {

    void aMethod() {

    C1 o = new C1();

    ?o.x;

    ?o.y;

    ?o.z;

    ?o.m1();

    ?o.m2();

    ?o.m3();

    }

    }

    public class C1 {

    public int x;

    int y;

    private int z;

    public void m1() {

    }

    void m2() {

    }

    private void m3() {

    }

    }

    public class C3 {

    void aMethod() {

    C1 o = new C1();

    ?o.x;

    ?o.y;

    ?o.z;

    ?o.m1();

    ?o.m2();

    ?o.m3();

    }

    }

    package p1;

    package p2;

    public class C2 {

    ?C1

    }

    class C1 {

    ...

    }

    public class C3 {

    ?C1;

    ?C2;

    }

    package p1;

    package p2;

  • The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.

    2004 Pearson Addison-Wesley. All rights reserved

    public class C2 {

    void aMethod() {

    C1 o = new C1();

    can access o.x;

    can access o.y;

    cannot access o.z;

    can invoke o.m1();

    can invoke o.m2();

    cannot invoke o.m3();

    }

    }

    public class C1 {

    public int x;

    int y;

    private int z;

    public void m1() {

    }

    void m2() {

    }

    private void m3() {

    }

    }

    public class C3 {

    void aMethod() {

    C1 o = new C1();

    can access o.x;

    cannot access o.y;

    cannot access o.z;

    can invoke o.m1();

    cannot invoke o.m2();

    cannot invoke o.m3();

    }

    }

    package p1;

    package p2;

    public class C2 {

    can access C1

    }

    class C1 {

    ...

    }

    public class C3 {

    cannot access C1;

    can access C2;

    }

    package p1;

    package p2;

  • NOTEAn object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).

    2004 Pearson Addison-Wesley. All rights reserved

    (a) This is OK because object foo is used inside the Foo class

    public class Foo {

    private boolean x;

    public static void main(String[] args) {

    Foo foo = new Foo();

    System.out.println(foo.x);

    System.out.println(foo.convert());

    }

    private int convert(boolean b) {

    return x ? 1 : -1;

    }

    }

    (b) This is wrong because x and convert are private in Foo.

    public class Test {

    public static void main(String[] args) {

    Foo foo = new Foo();

    System.out.println(foo.x);

    System.out.println(foo.convert(foo.x));

    }

    }

  • Examplepublic class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } }public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } }public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Method DeclarationsLets now examine method declarations in more detailA method declaration specifies the code that will be executed when the method is invoked (called)When a method is invoked, the flow of control jumps to the method and executes its codeWhen complete, the flow returns to the place where the method was called and continuesThe invocation may or may not return a value, depending on how the method is defined

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Method Control FlowIf the called method is in the same class, only the method name is needed

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Method Control FlowThe called method is often part of another class or object

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Method HeaderA method declaration begins with a method headerchar calc (int num1, int num2, String message)methodnamereturntypeparameter listThe parameter list specifies the typeand name of each parameter

    The name of a parameter in the methoddeclaration is called a formal parameter

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Method BodyThe method header is followed by the method bodychar calc (int num1, int num2, String message){ int sum = num1 + num2; char result = message.charAt (sum);

    return result;}The return expressionmust be consistent withthe return typesum and resultare local data

    They are created each time the method is called, and are destroyed when it finishes executing

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*The return StatementThe return type of a method indicates the type of value that the method sends back to the calling locationA method that does not return a value has a void return typeA return statement specifies the value that will be returnedreturn expression;Its expression must conform to the return type

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*ParametersWhen a method is called, the actual parameters in the invocation are copied into the formal parameters in the method headerch = obj.calc (25, count, "Hello");

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Bank Account ExampleLets look at another example that demonstrates the implementation details of classes and methodsWell represent a bank account by a class named AccountIts state can include the account number, the current balance, and the name of the ownerAn accounts behaviors (or services) include deposits and withdrawals, and adding interest

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Driver ProgramsA driver program drives the use of other, more interesting parts of a programDriver programs are often used to test other parts of the softwareThe Transactions class contains a main method that drives the use of the Account class, exercising its servicesSee Transaction.java See Account.java

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*public class Transaction {public static void main (String[] args){ Account acct1 = new Account ("Ted Murphy", 72354, 102.56); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct3 = new Account ("Edward Demsey", 93757, 759.32);

    acct1.deposit (25.85);

    double smithBalance = acct2.deposit (500.00); System.out.println ("Smith balance after deposit: " + smithBalance);

    System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50));

    acct1.addInterest(); acct2.addInterest(); acct3.addInterest();

    System.out.println (); System.out.println (acct1); System.out.println (acct2); System.out.println (acct3); }}

    import java.text.NumberFormat;

    public class Account{ private final double RATE = 0.035; // interest rate of 3.5% private long acctNumber; private double balance; private String name;public Account (String owner, long account, double initial) { name = owner; acctNumber = account; balance = initial; }public double deposit (double amount) { balance = balance + amount;

    return balance; }

    public double withdraw (double amount, double fee) { balance = balance - amount - fee;

    return balance; }

    public double addInterest () { balance += (balance * RATE); return balance; }

    public double getBalance () { return balance; }

    public String toString () { NumberFormat fmt = NumberFormat.getCurrencyInstance();

    return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); }}

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Outpu:t:

    Smith balance after deposit: 540.0Smith balance after withdrawal: 107.75

    72354 Ted Murphy MYR132.9069713 Jane Smith MYR111.5293757 Edward Demsey MYR785.90

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Bank Account Example

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Bank Account ExampleThere are some improvements that can be made to the Account classFormal getters and setters could have been defined for all dataThe design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Constructors RevisitedNote that a constructor has no return type specified in the method header, not even voidA common error is to put a return type on a constructor, which makes it a regular method that happens to have the same name as the classThe programmer does not have to define a constructor for a classEach class has a default constructor that accepts no parameters

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Graphical ObjectsSome objects contain information that determines how the object should be represented visuallyWe did this in Chapter 2 when we defined the paint method of an appletLet's look at some other examples of graphical objects

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Smiling Face ExampleThe SmilingFace program draws a face by defining the paintComponent method of a panelSee SmilingFace.java See SmilingFacePanel.java The main method of the SmilingFace class instantiates a SmilingFacePanel and displays itThe SmilingFacePanel class is derived from the JPanel class using inheritance (extends)

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Smiling Face ExampleThe SmilingFace panel is a JPanelIn the Constructor method we:Set the background colorSet the preferred sizeSet the fontThe JPanel has a paintComponent methodThis method automatically gets called to draw the panel

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Smiling Face ExampleEvery Swing component has a paintComponent methodThe paintComponent method accepts a Graphics object that represents the graphics context for the panelWe define the paintComponent method to draw the face with appropriate calls to the Graphics methodsNote the difference between drawing on a panel and adding other GUI components to a panel

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Smiling Face ExampleWe add to the definition of this method to also draw the face and the wordsThe first line of this method will almost always be: super.paintComponent (Graphics g);The super refers to the parent class

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Graphical User InterfacesA Graphical User Interface (GUI) in Java is created with at least three kinds of objects:componentseventslistenersWe've previously discussed components, which are objects that represent screen elements labels, buttons, text fields, menus, etc.Some components are containers that hold and organize other componentsframes, panels, applets, dialog boxes

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*EventsAn event is an object that represents some activity to which we may want to respondFor example, we may want our program to perform some action when the following occurs:the mouse is movedthe mouse is dragged a mouse button is clickeda graphical button is clickeda keyboard key is presseda timer expiresEvents often correspond to user actions, but not always

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Events and ListenersThe Java standard class library contains several classes that represent typical eventsComponents, such as a graphical button, generate (or fire) an event when it occursA listener object "waits" for an event to occur and responds accordinglyWe can design listener objects to take whatever actions are appropriate when an event occurs

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Events and ListenersWhen the event occurs, the component callsthe appropriate method of the listener,passing an object that describes the event

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*GUI DevelopmentGenerally we use components and events that are predefined by classes in the Java class libraryTherefore, to create a Java program that uses a GUI we must:instantiate and set up the necessary componentsimplement listener classes for any events we care aboutestablish the relationship between listeners and components that generate the corresponding events

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*OutlineAnatomy of a ClassEncapsulationAnatomy of a MethodGraphical ObjectsGraphical User InterfacesButtons and Text Fields

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*ButtonsA push button is a component that allows the user to initiate an action by pressing a graphical button using the mouseA push button is defined by the JButton classIt generates an action eventThe PushCounter example displays a push button that increments a counter each time it is pushed

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Push Counter ExampleThe components of the GUI are: The button The label to display the counter The panel to organize the components The main frame

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Push Counter ExampleAn interface is a list of methods that the implementing class must defineThe only method in the ActionListener interface is the actionPerformed methodThe Java class library contains interfaces for many types of events (chapter 6)The PushCounterPanel constructor:instantiates the ButtonListener objectestablishes relationship between button and listener with the call to: addActionListener

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Push Counter ExampleWhen the user presses the button:The button component creates: An ActionEvent object Calls the actionPerformed method of the listenerThis method increments the counter and resets the text of the label

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Text FieldsLet's look at another GUI example that uses another type of componentA text field allows the user to enter a line of inputIf the cursor is in the text field, the text field component generates an action event when the enter key is pressed

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Fahrenheit ExampleLike the PushCounter example, the GUI is set up in a separate panel classThe text field and labels are added to the panelThe panel is governed by the flow layout managerThe TempListener inner class defines the listener for the action event generated by the text fieldThe FahrenheitPanel constructor instantiates the listener and adds it to the text field

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*Fahrenheit ExampleWhen the user types a temperature and presses enter, the text field generates the action event and calls the actionPerformed method of the listenerThe method retrieves the text using: getText()This returns a character string and is converted to an integer by using the parseInt() methodThe actionPerformed method then computes the conversion and updates the result labelThe same listener object can listen to multiple components

    2004 Pearson Addison-Wesley. All rights reserved

  • 2004 Pearson Addison-Wesley. All rights reserved4-*SummaryChapter 4 focused on:class definitionsinstance dataencapsulation and Java modifiersmethod declaration and parameter passingconstructorsgraphical objectsevents and listenersbuttons and text fields

    2004 Pearson Addison-Wesley. All rights reserved