0% found this document useful (0 votes)
31 views

Defining Classes and Methods

The document discusses defining classes and methods in Java. It covers topics like class definitions, objects, instance variables, setters and getters, method definitions, parameters, and more. Code examples are provided to demonstrate key concepts around classes and methods.

Uploaded by

Birondo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Defining Classes and Methods

The document discusses defining classes and methods in Java. It covers topics like class definitions, objects, instance variables, setters and getters, method definitions, parameters, and more. Code examples are provided to demonstrate key concepts around classes and methods.

Uploaded by

Birondo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

• CpE 2101L : Object Oriented Programming

DEFINING CLASSES AND


METHODS

Unit 4
Unit 4: Defining Classes and Methods
• Class and Method Definitions
• Objects and References
• Instance Variables
• Setters and Getters
Class and Method
Definitions
UNIT 4: DEFINING CLASSES AND METHODS
Class and Method Definitions
• A class as a blueprint
Class and Method Definitions

Objects that are


instantiations of the
class Automobile
Class and Method Definitions
• A class outline as a UML class diagram
Class Files and Separate Compilation
• Each Java class definition usually in a file by
itself
• File begins with name of the class
• Ends with .java

• Class can be compiled separately


• Helpful to keep all class files used by a
program in the same directory
Dog class and Instance Variables
• Sample program list, 4.1
class Dog
• Note class has
• Three pieces of data (instance variables)
• Two behaviors
• Each instance of this type has its own copies of
the data items
• Use of public
• No restrictions on how variables used
• Later will replace with private
Using a Class and Its Methods
• Sample program, 4.1
class DogDemo

Sample
screen
output
Methods
• When you use a method you "invoke" or "call" it
• Two kinds of Java methods
• Return a single item
• Perform some other action – a void method

• The method main is a void method


• Invoked by the system
• Not by the application program
Methods
• Calling a method that returns a quantity
• Use anywhere a value can be used
• Calling a void method
• Write the invocation followed by a semicolon
• Resulting statement performs the action defined by
the method
Defining void Methods
• Consider method writeOutput

• Method definitions appear inside class definition


• Can be used only with objects of that class
Defining void Methods
• Most method definitions we will see as
public
• Method does not return a value
• Specified as a void method
• Heading includes parameters
• Body enclosed in braces { }
• Think of method as defining an action to be
taken
Methods That Return a Value
• Consider method getAgeInHumanYears( )

• Heading declares type of value to be returned


• Last statement executed is return
Second Example – Species Class
• Class designed to hold records of endangered
species
• Class listing, 4.2
class SpeciesFirstTry
• Three instance variables, three methods
• Will expand this class in the rest of the chapter
• Demo List, 4.2
class SpeciesFirstTryDemo
The Keyword this
• Referring to instance variables outside the class –
must use
• Name of an object of the class
• Followed by a dot
• Name of instance variable
• Inside the class,
• Use name of variable alone
• The object (unnamed) is understood to be there
The Keyword this
• Inside the class the unnamed object can be
referred to with the name this
• Example
this.name = keyboard.nextLine();
• The keyword this stands for the receiving
object
• We will seem some situations later that require
the this
Local Variables

• Variables declared inside a method are called


local variables
• May be used only inside the method
• All variables declared in method main are local to
main
• Local variables having the same name and
declared in different methods are different
variables
Local Variables
• Sample list, 4.3
class BankAccount
class LocalVariablesDemoProgram
• Note two different variables newAmount
• Note different values output
Sample
screen
output
Blocks
• Recall compound statements
• Enclosed in braces { }
• When you declare a variable within a compound
statement
• The compound statement is called a block
• The scope of the variable is from its declaration to the
end of the block
• Variable declared outside the block usable both
outside and inside the block
Parameters of Primitive Type
• Recall method
declaration
in listing 4.2
• Note it only works for 10 years
• We can make it more versatile by giving the method
a parameter to specify how many years
• Note sample program, 4.4
class SpeciesSecondTry
Parameters of Primitive Type
• Note the declaration
public int predictPopulation(int years)
• The formal parameter is years
• Calling the method
int futurePopulation =
speciesOfTheMonth.predictPopulation(10);
• The actual parameter is the integer 10
• Sample listing,
class SpeciesSecondClassDemo
Parameters of Primitive Type
• Parameter names are local to the method
• When method invoked
• Each parameter initialized to value in corresponding
actual parameter
• Primitive actual parameter cannot be altered by
invocation of the method
• Automatic type conversion performed
byte -> short -> int ->
long -> float -> double
Pre- and Postcondition Comments
• Precondition comment
• States conditions that must be true before method is
invoked
• Example
Pre- and Postcondition Comments
• Postcondition comment
• Tells what will be true after method executed
• Example
The public and private Modifiers
• Type specified as public
• Any other class can directly access that object by
name
• Classes generally specified as public
• Instance variables usually not public
• Instead specify as private
Accessor and Mutator Methods
• When instance variables are private must
provide methods to access values stored there
• Typically named getSomeValue
• Referred to as an accessor method
• Must also provide methods to change the
values of the private instance variable
• Typically named setSomeValue
• Referred to as a mutator method
Methods Calling Methods
• A method body may call any other method
• If the invoked method is within the same class
• Need not use prefix of receiving object
Automatic Documentation javadoc
• Generates documentation for class interface
• Comments in source code must be enclosed in
/** */
• Utility javadoc will include
• These comments
• Headings of public methods
• Output of javadoc is HTML format
UML Class Diagrams
• Recall a class outline as a UML class diagram
UML Class Diagrams
• Purchase
class
Minus signs imply
private access

Plus signs imply


public access
UML Class Diagrams
• Contains more than interface, less than full
implementation
• Usually written before class is defined
• Used by the programmer defining the class
• Contrast with the interface used by programmer who
uses the class
Objects and References
UNIT 4: DEFINING CLASSES AND METHODS
Objects and References
• Variables of a Class Type
• Defining an equals Method for a Class
• Boolean-Valued Methods
• Parameters of a Class Type
Variables of a Class Type
• All variables are implemented as a memory
location
• Data of primitive type stored in the memory
location assigned to the variable
• Variable of class type contains memory
address of object named by the variable
Variables of a Class Type
• Object itself not stored in the variable
• Stored elsewhere in memory
• Variable contains address of where it is stored
• Address called the reference to the variable
• A reference type variable holds references
(memory addresses)
• This makes memory management of class types
more efficient
Variables of a Class Type
• Behavior
of class
variables
Variables of a Class Type
• Behavior
of class
variables
Variables of a Class Type
• Behavior
of class
variables
Variables of a Class Type
• Behavior
of class
variables
Variables of a Class Type
• Dangers of
using ==
with objects
Variables of a Class Type
• Dangers of
using ==
with objects
Defining an equals Method
• As demonstrated by previous figures
• We cannot use == to compare two objects
• We must write a method for a given class which will
make the comparison as needed
• Sample code listing 4.5
class Species
• The equals for this class method used same
way as equals method for String
Demonstrating an equals Method
• Sample program, listing 4.5
class SpeciesEqualsDemo
• Note difference in the two comparison methods
== versus .equals( )

Sample
screen
output
Boolean-Valued Methods
• Methods can return a value of type boolean
• Use a boolean value in the return statement
Parameters of a Class Type
• When assignment operator used with objects of
class type
• Only memory address is copied
• Similar to use of parameter of class type
• Memory address of actual parameter passed to
formal parameter
• Formal parameter may access public elements of the
class
• Actual parameter thus can be changed by class
methods
Programming Example
• Sample program, listing 4.6
class DemoSpecies
• Note different parameter types and results

class ParametersDemo
• Parameters of a class type versus parameters of a
primitive type
Programming Example

Sample
screen
output
Programming Example
• UML Diagram
Programming Example
setDimension(double , double ): void
• Method to set the length and width of the rectangle.
getLength() const: double
• Method to return the length of the rectangle.
getWidth() const: double
• Method to return the width of the rectangle.
area() const: double
• Method to return the area of the rectangle.
Programming Example
perimeter() const: double
• Method to return the perimeter of the rectangle.
print() const: void
• Method to output the length and width of the rectangle.
rectangleType()
• default constructor; set length and width to zero
rectangleType(double , double )
• constructor with parameters; length = l; width = w;

double length
double width
(optional)
Graphics Supplement
• The Graphics Class
• The init Methods
• Adding Labels to an Applet
The Graphics Class
• An object of the Graphics class represents
an area of the screen
• Instance variables specify area of screen
represented
• When you run an Applet
• Suitable Graphics object created automatically
• This object used as an argument in the paint
method
The Graphics Class
• Some methods in class Graphics
The Graphics Class
• Some methods in class Graphics
Programming Example
• Multiple faces – using a Helping method
class MultipleFaces

Sample
screen
output
The init Method
• Method init may be defined for any applet
• Like paint, method init called
automatically when applet is run
• Method init similar to method main in an
application program
Adding Labels to Applet
• Provides a way to add text to an applet
• When component (such as a label) added to an
applet
• Use method init
• Do not use method paint
Adding Labels to Applet
class LabelDemo

Sample
screen
output
References
• Walter Savitch
• Java : An Introduction to Problem Solving and
Programming 6th ed. Boston, Pearson Education ©
2015

You might also like