420 likes | 436 Views
Chapter 4: Writing classes. Writing classes . We have been using predefined classes Classes developed by SUN From the Java standard class library Used for the particular functionality they provided Example of predefined classes: String class defined in java.lang package
E N D
Writing classes • We have been using predefined classes • Classes developed by SUN • From the Java standard class library • Used for the particular functionality they provided • Example of predefined classes: • String class defined in java.lang package • Now, we will learn to write our own classes • To define objects
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields
Own classes • Although • Existing class libraries provide many useful classes • Still • Essence of object oriented programming development • => design and implement your own classes • Why? In an attempt to suit your specific needs
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields
Relationship between an object and a class • Class • Blueprint of an object • The blueprint defines the important characteristics of object • Blueprint of a house defines (walls, windows, doors, etc) • Once blueprint created => use it to build objects (houses) • represents the concept of an object • Any object created is a realization of the concept • Example • String class (concept) => • String object (specific characters)
Another example • Suppose a class • Called student represents a particular student • Student is the general concept of a student • who has (name, address, Major, GPA) • To whom you need (to set address, major, compute GPA) • Every object created => an actual student • In a system • that helps manage the business of a university • one student class and 1000s of student objects
Object • An object • has a state defined • by the attributes associated with that object • Attributes of student => Student’s name, address, major, etc.. • stores the values of attributes for a particular student • whose attributes defined • by variables declared within a class
Object (cont’d) • An object • has behaviors • defined by the operations associated with that object • Operations of a student => update student’s address, GPA etc • executes the operations defined by the class • whose operations defined • by methods declared within a class
int size, weight; char category; Classes • A class can contain data declarations • And method declarations Data declarations Method declarations
Classes and objects • Consider a six-sided die (singular of dice) • its state can be defined as which face is showing • its primary behaviour is that it can be rolled • We can represent a die in software • By designing a class called Die that • models this state and behaviour • This class would serve as the blueprint for a die object • We can then instantiate • As many die objects as we need for our program
Class design • For our Die class • We might declare an integer that • Represents the current value showing on the face • One of the methods would • roll the die by setting that value to a random number • Between one and six
Classes • We’ll want to design the Die class • with other data and methods • to make it a versatile and reusable resource • Any given program will not necessarily use • all aspects of a given class • See RollingDice.java • See Die.java
The Die Class • The Die class contains two data values • a constant MAX that represents the maximum face value • an integer faceValue that represents • the current face value • The roll method uses the random method • of the Math class to determine a new face value • There are also methods to • explicitly set and retrieve the current face value at any time
Constructors • A constructor is a special method • that is used to set up an object when it is initially created • A constructor has the same name as the class • The Die constructor is used • to set the initial face value of each new die object to one
The toString Method • All classes that represent objects • should define a toString method • The toString method • returns a character string that • represents the object in some way • It is called automatically when • an object is concatenated to a string • or when it is passed to the println method
Data Scope • The 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 class • Data declared in a method • can be used only in that method • Data declared within a method is called local data • In the Die class, • the variable result is declared • inside the toString method -- it is local to that method and cannot be referenced anywhere else
Instance Data • The faceValue variable in the Die class • is called instance data because each instance (object) • that is created has its own version of it • A class declares the type of the data, • but it does not reserve any memory space for it • Every time a Die object is created, • a new faceValue variable is created as well • The objects of a class share the methods • but each object has its own data space • That's the only way two objects can have different states
die1 faceValue 5 die2 faceValue 2 Instance Data • We can depict the two Die objects as follows Each object maintains its own faceValue variable, and thus its own state
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Encapsulation • We can take one of two views of an object • Internal • The details of the variables and methods of the class • That defines it • External • The services that an object provides and how • The object interacts with the rest of the system • From the external view, an object • an encapsulated entity, providing set of specific services • These services define the interface to the object
Encapsulation (cont’d) • An object • Should be self-governing • => data of object modified only by the object itself • The methods of Die class sole responsible • for changing the value of faceValue • We should make it difficult for code outside class • To change the value of a variable declared inside class • => encapsulation
Methods Client Data Encapsulated object • The code using the object • Is called client of the object • Should not be allowed to access variables directly • Uses the methods instead to interact with data • Object encapsulation is achieved • Using visibility modifiers
Visibility modifiers • A modifier is a Java reserved word • That specifies the characteristics of a method or data • Controls access to the members of a class • Java has two main visibility modifiers • public: members of a class declared as public • Can be referenced anywhere • private: members of a class declared as private • Can only be referenced within the class
Private variables • Public variables • Violate encapsulation because • They allow the client to reach in and modify values directly • => variables should not be declared with public visibility • => declared as private • Methods that provide object’s services • Are declared with public visibility • So that they can be invoked by clients
Accessors and mutators • Data is generally private • => class provides services to • Access data values through accessor methods • Ex: getFaceValue()read only access to a particular value • Modify data values through mutator methods • Ex: setFaceValue changes a particular value • These types of methods are sometimes • Referred to as “getters” and “setters” • The name of an accessor method take the form getX • Where X is the name of value • The name of a mutator method take the form setX
methods • A method • is a group of statements that is given a name • specifies the code executed, when method is called • One by one, the statements of that method are executed • When done, control returns to the location of the call • And execution continues • its header includes • The type of return value + method name + (list of parameters)
method invocations • If called method and calling method • Same class => only method name is needed • Different class => invoke through the name of other class main helpMe doThis obj.doThis(); helpMe();
Method Header • A method declaration begins with a method header char calc (int num1, int num2, String message) method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter return type
Method Body • The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type
Return type • Return type specified in method header • Primitive type or class name • When the method returns a value • In this case, the method must have a return statement • Return statement : return + value to be returned • Or, the reserved word “void” • When a method does not return any value • In this case, the method does not contain a return statement • Control is returned to calling method at the end of the method
The return Statement • The return type of a method indicates • the type of value that the method • sends back to the calling location • method returning no value has a void return type • A return statement • specifies the value that will be returned return expression; • Its expression must conform to the return type
Return type • Return type specified in method header • Primitive type or class name • When the method returns a value • In this case, the method must have a return statement • Return statement : return + value to be returned • Or, the reserved word “void” • When a method does not return any value • In this case, the method does not contain a return statement • Control is returned to calling method at the end of the method
parameters • The parameter list in the header of a method • Specifies • The types of the values passed to the method • And the names by which the method refer to those values • given in parentheses after the method name • If empty, an empty set of parentheses is used
Local Data • Local variables can be declared inside a method • The parameters of a method • create automatic local variables when method is invoked • When the method finishes, • all local variables are destroyed • Instance variables declared at the class level • exists as long as the object exists
Bank Account Example • Example demonstrates • implementation details of classes and methods • represent bank account by a class named Account • State can include • the account number, the current balance, • and the name of the owner • An account’s behaviors (or services) • include deposits and withdrawals, and adding interest
Driver Programs • A driver program drives • the use of other, more interesting parts of a program • Driver programs are often used • to test other parts of the software • The Transactions class contains a main method • drives the use of the Account class, • exercising its services • See Transactions.java (page 172) • See Account.java (page 173)
acct1 72354 acctNumber 102.56 balance “Ted Murphy” name acct2 69713 acctNumber 40.00 balance “Jane Smith” name Bank Account Example
Bank Account Example • There are some improvements that can be made to the Account class • Formal getters and setters could have been defined for all data • The design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive
Constructors revisited • When we define a class • We usually define a constructor • A method that helps setting the class up • Often used to initialize variables associated with each object • Constructors differ from regular method • The name of constructor is the same as the class • A constructor cannot return a value • Does not have a return type • A common mistake is to put a void return type on a constructor
Constructors revisited (cont’d) • Constructor • is used to initialize the newly instantiated object • Don’t have to define a constructor for every class • Each class has a default constructor taking no parameters • This default constructor is used if you don’t provide your own • Default constructor has no effect on the newly created object