Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4: Writing classes

Similar presentations


Presentation on theme: "Chapter 4: Writing classes"— Presentation transcript:

1 Chapter 4: Writing classes

2 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

3 Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields

4 Own classes Although Still
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

5 Outline Anatomy of a Class Encapsulation Anatomy of a Method
Graphical Objects Graphical User Interfaces Buttons and Text Fields

6 Relationship between an object and a 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)

7 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

8 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

9 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

10 Examples of classes and possible attributes and operations
Rectangle Length Width Color Set length Set width Set color Flight Airline Flight number Origin city Destination city Set airline Set flight number Set origin city Set destination city Employee Name Department Salary Set name Set department Compute bonus Compute taxes

11 Classes A class can contain data declarations And method declarations
int size, weight; char category; Data declarations Method declarations

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 Instance Data We can depict the two Die objects as follows die1 5
faceValue die2 2 Each object maintains its own faceValue variable, and thus its own state

21 Outline Anatomy of a Class Encapsulation Anatomy of a Method

22 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

23 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

24 Encapsulated object The code using the object
Methods Data Client 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

25 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

26 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

27 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

28 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)

29 method invocations If called method and calling method
main helpMe doThis obj.doThis(); helpMe(); If called method and calling method Same class => only method name is needed Different class => invoke through the name of other class

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 Driver Programs A driver program drives Driver programs are often used
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)

39 Bank Account Example acct1 acctNumber 72354 balance 102.56 name
“Ted Murphy” acct2 69713 acctNumber 40.00 balance name “Jane Smith”

40 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

41 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

42 Constructors revisited (cont’d)
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


Download ppt "Chapter 4: Writing classes"

Similar presentations


Ads by Google