Title: CSCI102 An Introduction to Programming using Java
1CSCI102 An Introduction to Programming using
Java
2Chapter 4
- Defining Classes and Methods
3Objects
-
- An object is a variable of a class type.
- Objects have data but they also can perform
actions. - Actions performed by objects are known as
methods. (We have already used objects of the
String class which is supplied with the Java
language).
4- This week and next week you will learn how to
define your own classes, and how to use objects
of those classes.
5Chapter 4
- 4.1 Class and Method Definitions
- 4.2 Information Hiding and Encapsulation
- 4.3 Objects and Reference
6Chapter 4
- 4.1 Class and Method Definitions
- 4.2 Information Hiding and Encapsulation
- 4.3 Objects and Reference
7Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
8Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
9Class Files and Separate Compilation
- Each Java class definition has to be in a file by
itself. - The name of the file must match the name of the
class, and have the extension .java - After successfully compiling the class, the byte
code is stored in a file with the same name, but
with the extension .class
10- To use a class in a Java application program,
there must be a .java file containing the main
program part. I will call this the main program
file. - The main program file also has a class name at
the start of the file, and has a file name to
match, with the extension .java.
11A Class Definition SpeciesFirstTry.java
- http//www.annedawson.net/SpeciesFirstTry.java
- page 225 of 4th Ed textbook
12Using Classes and Methods SpeciesFirstTryDemo.jav
a
- http//www.annedawson.net/SpeciesFirstTryDemo.java
- page 227 of 4th Ed textbook
13Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
14Instance Variables
- Objects have data items and methods.
15an instance variable is a data item
16Examples of instance variables
- public String employee
- public double salary
- public int languages
17the keyword public
- public String employee
- The keyword public means that the variable
employee can be used anywhere.
18Declaring Instance VariablesSpeciesFirstTryDemo.
java
- http//www.annedawson.net/SpeciesFirstTryDemo.java
- page 227 of 4th Ed textbook
19To create a new object
- Car fastcar new Car()
- Assigns memory for the object called fastcar
20To access the value of an instance variable of an
object
- fastcar.color
- object (dot) instance variable
21To invoke (call) a method of an object, the dot
is used again
- fastcar.move()
- object (dot) method
22Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
23To invoke (call) a method of an object
- fastcar.move()
- object (dot) method
24Another way to call a method
- For some special methods (called static or
class methods - see text book) you can call the
method using - Classname.methodname( )
- e.g.
- int result Math.max(n1,n2)
25Static Methods
- The SavitchIn class uses static methods for
- data input. . .
26Calling a static method
- SavitchIn.readLineInt()
- Class (dot)
method -
27There are only two kinds of methods
- those that return a value....
- ...and those that don't
28A method that does not return a value looks like
this
- public void writeOutput()
-
- System.out.println("Name " name)
- System.out.println("Pop " pop)
-
29Calling a method that does not return a value
- speciesOfTheMonth.writeOutput()
- object (dot)
method
30Calling a method that returns a value
- data flow
- number_of_cars SavitchIn.readLineInt()
31Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
32A method that returns a value
- number_of_cars SavitchIn.readLineInt()
33A sample definition of a method that returns a
value . . .
34- public int populationIn10()
-
- double populationAmount population
- int count 10
- while ((count gt 0) (populationAmount gt 0))
-
- populationAmount (populationAmount
- (growthRate/100) populationAmount)
- count--
-
- if (populationAmount gt 0)
- return (int)populationAmount // (type cast)
- else
- return 0
-
35- public int populationIn10()
-
- double populationAmount population
- int count 10
- while ((count gt 0) (populationAmount gt 0))
-
- populationAmount (populationAmount
- (growthRate/100) populationAmount)
- count--
-
- if (populationAmount gt 0)
- return (int)populationAmount // (type cast)
- else
- return 0
-
36Please Note!
- Although void methods cannot return a value,
you can still use the return statement to exit
the method . See page 237 (4th Ed) of the text
book for a description of this.
37Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
38- Outside of a method definition an instance
variable is normally accessed with reference to
the object which owns it, e.g. - fastcar.color
39- On the other hand, inside of a method
definition instance variables can be referred to
by just their name, e.g. - color
- after all, the name of the calling object is
not known within the method definition, but it is
understood that an object will be involved at
some point (i.e. when the method is called).
40- Inside of a method definition, instance
variables can be referred to by just their name,
e.g. color - Should you wish to explicitly refer to the
calling object from inside the method definition,
the keyword this is used as a placeholder for
that calling object - this.color
41The reserved word this
- The reserved word (keyword) this stands for
the name of the calling object. It is used
inside a method definition. - Most of the time you don't need to use it.
Later you will see examples of when you do need
to use this.
42Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
43Local Variables
- A variable declared within a method definition
is called a local variable.
44Local Variables
- A local variable can only be used in the method
where it is declared.
45Local Variables
- If two methods each have a local variable of
the same name, then these are two different
variables even though they have the same name.
They occupy different areas in memory.
46Java has no global variables! (which is a good
thing)
47Blocks
- A block is a compound statement with variable
declarations. . .
48A block example
-
- String name "Anne"
- int age 21
- System.out.println(name age)
- // a compound statement is a
- // series of statements enclosed
- // in curly braces
49Blocks
- A block is a compound statement with variable
declarations. . .
50Blocks
- Variables declared within a block are local to
that block. . .
51 Warning!
- In Java you cannot use the same name twice
within the same method - even when they are in
different blocks!
52Class and Method Definitions
- Class Files and Separate Compilation
- Instance Variables
- Using Methods and void- Method Definitions
- Methods that Return a Value
- The this Parameter
- Local Variables and Blocks
- Parameters of a Primitive Type
-
53Using a Method with a Parameter
SpeciesSecondTry.java
- http//www.annedawson.net/SpeciesSecondTry.java
- page 244 of 4th Ed textbook
54Call-By-Value
- If the parameter is a primitive type (char,
int - etc) then the parameter is passed
call-by-value. - This means that the value of the variable is
passed, not the variable itself. Any changes
made to that value within the method do not
affect the variable which was passed to the
method.
55The formal parameter
- is a local variable in the method
56Note!
- Formal parameters have a type, and you should
aim to ensure that the data passed to the method
matches this type. - If you do not pass the matching type, Java
will attempt to perform a type cast into the
required type.
57Note!
- Multiple arguments are matched to multiple
formal parameters by position. . .
58- // the header of the method definition
- public void doThis(int n1, int n2, double cost,
char code) - anObject.doThis(42,100,9.99,'A')
- // calling the method
59Chapter 4
- 4.1 Class and Method Definitions
- 4.2 Information Hiding and Encapsulation
- 4.3 Objects and Reference
60Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
61Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
62Abstraction
- abstraction is the result of converting a
complex thing into a simple thing. . .
63Abstraction Example
- What has four walls, a door, windows and a
roof?
64Abstraction
- means listing the essentials and hiding the
details - the opposite of abstract means to show all the
details of an object
65Abstraction IS Information Hiding
66Information Hiding ISAbstraction
67Information Hiding ISEncapsulation
68Why is abstraction used in Java programs?
- Abstraction is used in a programming language
to make it easier for the programmer to focus on
the essential parts of a program, and not get
bogged down by the details.
69Why is abstraction used in Java programs?
- Hiding information simplifies programs by
grouping together data relevant to an object and
hiding the data from other objects (or
programmers). . .
70- A programmer can use the methods of a class
which was written by another programmer without
even seeing the source code. - All a programmer needs to know is what data is
required as input to the method, and what data
(if any) is returned.
71The Black Box Analogy
known inputs
known outputs
72Abstraction in Programming
- To use a method of a class, all a programmer
needs to know is what data is required as input
to the method, and what data (if any) is returned.
73- The information about the input and output
data of a method are known as the method's
preconditions and postconditions, respectively.
74The Black Box Analogy
postconditions
preconditions
known inputs
known outputs
75Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
76Documentation of Methods
- Preconditions and postconditions of methods
are usually documented as comments just above the
method definition in the source code.
77Precondition and Postcondition Comments
- /
- Precondition years is a nonnegative number.
- Returns the projected population of the calling
object - after the specified number of years.
- /
78- By commenting pre- and postconditions in this
manner, documentation for the method can be
automatically generated using the Sun
Microsystems application javadoc - javadoc is part of the Java SDK, and hence
should be located on your hard drive.
79javadoc
- See
- http//www.annedawson.net/javadoc.htm
80Documentation produced by javadoc. . .
- . . . is all a programmer needs to study in
order to use a class (and its methods) written by
somebody else.
81- If you give a .class file to another
programmer, with the documentation produced by
javadoc, the programmer can use the class without
having to study the source code. Indeed, they do
not need the .java source code in order to use
the class.
82You do not need the source code to be able to use
a class
- This is like saying that you don't need to
know the details of how a calculator works to be
able to use it. It's what you put in and what
comes out that matters. How the calculator does
it is irrelevant.
83Buying classes from a software vendor
- You can buy classes from software vendors, to
use with your program, saving you the job of
writing them yourself. The vendor gives you the
bytecode (.class) file (which is a binary file,
and hence does not contain any source code), and
documentation on how to use it.
84Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
85public and private Modifiers
- The public and private modifiers specify
where the variable being declared, or function
being defined, can be accessed. . .
86The Public Modifier
- Variables declared (or methods defined) using
the Public modifier, can be accessed anywhere in
a program or class.
87The Private Modifier
- Variables declared (or methods defined) using
the Private modifier, can only be accessed by a
method defined in the same class.
88Using Public and Private
- In general, all instance variables are Private
and all methods are Public.
89private variables - public methods
- There are a few exceptions. For example
'helper' methods are usually private. See page
267 (4th Ed) of the text book.
90Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
91Accessor Methods
- An accessor method is a method that allows you
to read or to set one or more instance variables.
92A Class With Accessor Methods SpeciesFourthTry.ja
va
- http//www.annedawson.net/SpeciesFourthTry.java
- page 258 of 4th Ed textbook
93Using an Accessor Method SpeciesFourthTryDemo.jav
a
- http//www.annedawson.net/SpeciesFourthTryDemo.jav
a - page 259 of 4th Ed textbook
94Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
95Abstract Data Types
- An abstract data type (ADT) is a data type (a
class) which exhibits information hiding and
encapsulation.
96When you write your own classes
- make sure that each class is an abstract data
type!
97Implementing an ADT
- 1. summarize the purpose of the class in
- comments at the top of the .java file
- 2. make instance variables private
- 3. provide public accessor and I/O methods.
- 4. write pre- and post-condition comments for
- every method
- 5. make helping methods private
98A class which is an ADT
- has two parts
- interface
- and
- implementation
99The ADT Interface
- The interface is simply the set of method
headers and associated comments. - These define the 'behaviour' of the class.
Put another way, the interface specifies how to
interact with objects of this class.
100A class which is an ADT
- has two parts
- interface
- and
- implementation
101Implementation
- The implementation is simply the code.
102Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
103Encapsulation
- Encapsulation means that the data and
functions relevant to an object, are stored
together as a single item, and the details are
hidden.
104Information Hiding and Encapsulation
- Information Hiding and Abstraction
- Precondition and Postcondition Comments
- Public and Private Modifiers
- Private Methods and Accessor Methods
- Abstract Data Types and User Interface
- Encapsulation
- Automatic Documentation with javadoc
105Automatic Documentation with javadoc
- javadoc is a program provided free with Sun
Microsystem's implementation of java. When you
run javadoc, a document is generated which
describes the user interface to your classes.
106javadoc
- See
- http//www.annedawson.net/javadoc.htm
107Chapter 4
- 4.1 Class and Method Definitions
- 4.2 Information Hiding and Encapsulation
- 4.3 Objects and Reference
108Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
109Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
110Variables of a Class Type and Objects
- A variable of a class type
- is an object.
111To create an object
- Syntax
- Classname objectname new Classname()
- Examples
- Animal dog new Animal()
- Animal cat new Animal()
112To create an object
- Classname objectname new Classname( )
- is the short version of
- Classname objectname // declares a name to
- // hold the
- // address of the object
- objectname new Classname( ) //object
- //created
113- The name of any object is the address of the
first member.
114- If you remember the preceding statement
whenever you're programming with objects, you'll
save yourself a lot of grief.
115To create an object
- Classname objectname new Classname()
-
This is the default constructor, (explained
in the next chapter) which is a special
initializing method which, amongst other
things, - returns the start address in memory
-
of the new object.
116When an object is referred to in a program, for
example. . .
- objectname.set(100)
-
- you are actually
- referring to an address,
- not any value within the object.
117Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
118The new keyword
-
- The new keyword allocates memory for the
object, placing the start address in the object's
variable name. . .
119- Because variables of a class type hold
addresses, they behave very differently to
variables of a primitive type (which hold values
of their own type). . .
120Differences between class objects and primitive
objects
- int num1 6
- int num2 9
- num1 num2 // puts 9 into num1
- Animal cat new Animal()
- // puts an address into cat
- Animal dog new Animal()
- // puts another address into dog
- cat dog // they both hold the address
- // of the dog object, hence now cat
- // and dog refer to the dog object
- cat dog // returns true
121- The name of any object is the
- address of the first member.
122- The name of any primitive is its value.
num1
9
123Differences between class objects and primitive
objects
- int num1 6
- int num2 9
- num1 num2 // puts 9 into num1
- Animal cat new Animal()
- // puts an address into cat
- Animal dog new Animal()
- // puts another address into dog
- cat dog // they both hold the address
- // of the dog object, hence now cat
- // and dog refer to the dog object
- cat dog // true
124cat dog
-
- The above line compares addresses. If you
want to compare objects of the same class, you
should define your own equals method for the
class, with a usage - obj1.equals(obj2)
- See page 275 (4th Ed) of the text book.
125The equals method
- If you do not define an equals method for your
class, then Java will automatically create a
default definition of equals, but it is unlikely
to behave the way you want it to behave. -
126The equals method
- Always define your own equals method.
127Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
128Defining an equals Method Species.java
- http//www.annedawson.net/Species.java
- page 277 of 4th Ed textbook
129Demonstrating an equals Method
SpeciesEqualsDemo.java
- http//www.annedawson.net/SpeciesEqualsDemo.java
- page 278 of 4th Ed textbook
130Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
131Parameters of a Class Type
- Firstly, let's just remind ourselves of
parameters of a primitive type...
132Parameters of a Primitive Type
- public int multiply_by_two (int number)
-
- int double_it
- double_it number number
- return double_it
-
- to call the method n multiply_by_two(num1)
133The value of num1 is not changed by the method.
- public int multiply_by_two (int number)
-
- int double_it
- double_it number number
- return double_it
-
- to call the method n multiply_by_two(num1)
134The name of any primitive variable is the value
it contains!
- public int multiply_by_two (int number)
-
- int double_it
- double_it number number
- return double_it
-
- to call the method n multiply_by_two(num1)
135Inside the function, number is a local variable
which takes a copy of the value of num1.
- public int multiply_by_two (int number)
-
- int double_it
- double_it number number
- return double_it
- // end of method definition
- to call the method n multiply_by_two(num1)
136Call-By-Value
- When primitive types are used as arguments to
methods, it is known as.....
137Parameters of a Class Type
- Parameters of a class type behave very
differently to parameters of a primitive type....
138Parameters of a Class Type
public void do_something_to(Animal thing) //
whatever happens to thing within // this
method actually // happens to cat. These
are // permanent changes to cat //
because the method receives cat's //
address. It is as if the method // receives
the cat object itself. // end of method
definitionmethod call do_something_to(cat)
139- The name of any object is the address of the
first member.
140Call-By-Reference?
- Some people call passing a class object to a
method as call-by-reference, but this is not
strictly true. (Aside for C programmer's -
this is like saying an array parameter is not
exactly call-by-reference.) -
There are similarities, but there are also
important differences. Hence for correctness, we
will not refer to class parameters as
call-by-reference.
141Objects and Reference
- Variables of a Class Type and Objects
- the new keyword
- Boolean valued methods
- Parameters of a class type
- Comparing Class and Primitive type parameters
142Comparing Class and Primitive-Type Parameters
- A method cannot change the value of a
primitive type that is an argument to the method. - On the other hand, a method can change the
values of the instance variables of an argument
of a class type.
143And finally...
- The constant value null is a special constant
that can be used to give a value to any variable
of any class type. - null is a sort of placeholder for an address,
but it is not an address itself. You can use - and ! to compare objects with null,
- eg (cat ! null)
144This Presentation uses the following files
- 4th Ed 3rd 2nd
1st - SavitchIn.java p1013
- SpeciesFirstTry.java p225 p185 p214
p158 - SpeciesFirstTryDemo.java p227 p187 p217
p159 - SpeciesSecondTry.java p244 p204 p234
p177 - SpeciesSecondTryDemo.java p245 p205 p235
p178 - SpeciesFourthTry.java p258 p218 p249
p192 - SpeciesFourthTryDemo.java p259 p219 p250
p193 - Species.java p277 p237 p272
p210 - SpeciesEqualsDemo.java p278 p238 p273
p211 -
145End of Java_Classes_Ch04.ppt
146- Last updated Friday 12th September 2008, 707
PT, AHD