CSCI102 An Introduction to Programming using Java - PowerPoint PPT Presentation

1 / 146
About This Presentation
Title:

CSCI102 An Introduction to Programming using Java

Description:

Car fastcar = new Car(); Assigns memory for the object called fastcar. 11/5 ... variable is normally accessed with reference to the object which owns it, e.g. ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 147
Provided by: AnneD71
Category:

less

Transcript and Presenter's Notes

Title: CSCI102 An Introduction to Programming using Java


1
CSCI102 An Introduction to Programming using
Java
2
Chapter 4
  • Defining Classes and Methods

3
Objects
  • 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.

5
Chapter 4
  • 4.1 Class and Method Definitions
  • 4.2 Information Hiding and Encapsulation
  • 4.3 Objects and Reference

6
Chapter 4
  • 4.1 Class and Method Definitions
  • 4.2 Information Hiding and Encapsulation
  • 4.3 Objects and Reference

7
Class 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

8
Class 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

9
Class 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.

11
A Class Definition SpeciesFirstTry.java
  • http//www.annedawson.net/SpeciesFirstTry.java
  • page 225 of 4th Ed textbook

12
Using Classes and Methods SpeciesFirstTryDemo.jav
a
  • http//www.annedawson.net/SpeciesFirstTryDemo.java
  • page 227 of 4th Ed textbook

13
Class 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

14
Instance Variables
  • Objects have data items and methods.

15
an instance variable is a data item
16
Examples of instance variables
  • public String employee
  • public double salary
  • public int languages

17
the keyword public
  • public String employee
  • The keyword public means that the variable
    employee can be used anywhere.

18
Declaring Instance VariablesSpeciesFirstTryDemo.
java
  • http//www.annedawson.net/SpeciesFirstTryDemo.java
  • page 227 of 4th Ed textbook

19
To create a new object
  • Car fastcar new Car()
  • Assigns memory for the object called fastcar

20
To access the value of an instance variable of an
object
  • fastcar.color
  • object (dot) instance variable

21
To invoke (call) a method of an object, the dot
is used again
  • fastcar.move()
  • object (dot) method

22
Class 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

23
To invoke (call) a method of an object
  • fastcar.move()
  • object (dot) method

24
Another 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)

25
Static Methods
  • The SavitchIn class uses static methods for
  • data input. . .

26
Calling a static method
  • SavitchIn.readLineInt()
  • Class (dot)
    method

27
There are only two kinds of methods
  • those that return a value....
  • ...and those that don't

28
A method that does not return a value looks like
this
  • public void writeOutput()
  • System.out.println("Name " name)
  • System.out.println("Pop " pop)

29
Calling a method that does not return a value
  • speciesOfTheMonth.writeOutput()
  • object (dot)
    method

30
Calling a method that returns a value
  • data flow
  • number_of_cars SavitchIn.readLineInt()

31
Class 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

32
A method that returns a value
  • number_of_cars SavitchIn.readLineInt()

33
A 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

36
Please 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.

37
Class 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

41
The 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.

42
Class 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

43
Local Variables
  • A variable declared within a method definition
    is called a local variable.

44
Local Variables
  • A local variable can only be used in the method
    where it is declared.

45
Local 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.

46
Java has no global variables! (which is a good
thing)
47
Blocks
  • A block is a compound statement with variable
    declarations. . .

48
A 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

49
Blocks
  • A block is a compound statement with variable
    declarations. . .

50
Blocks
  • 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!

52
Class 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

53
Using a Method with a Parameter
SpeciesSecondTry.java
  • http//www.annedawson.net/SpeciesSecondTry.java
  • page 244 of 4th Ed textbook

54
Call-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.

55
The formal parameter
  • is a local variable in the method

56
Note!
  • 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.

57
Note!
  • 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

59
Chapter 4
  • 4.1 Class and Method Definitions
  • 4.2 Information Hiding and Encapsulation
  • 4.3 Objects and Reference

60
Information 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

61
Information 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

62
Abstraction
  • abstraction is the result of converting a
    complex thing into a simple thing. . .

63
Abstraction Example
  • What has four walls, a door, windows and a
    roof?

64
Abstraction
  • means listing the essentials and hiding the
    details
  • the opposite of abstract means to show all the
    details of an object

65
Abstraction IS Information Hiding
66
Information Hiding ISAbstraction
67
Information Hiding ISEncapsulation
68
Why 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.

69
Why 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.

71
The Black Box Analogy
known inputs
known outputs
72
Abstraction 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.

74
The Black Box Analogy
postconditions
preconditions
known inputs
known outputs
75
Information 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

76
Documentation of Methods
  • Preconditions and postconditions of methods
    are usually documented as comments just above the
    method definition in the source code.

77
Precondition 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.

79
javadoc
  • See
  • http//www.annedawson.net/javadoc.htm

80
Documentation 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.

82
You 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.

83
Buying 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.

84
Information 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

85
public and private Modifiers
  • The public and private modifiers specify
    where the variable being declared, or function
    being defined, can be accessed. . .

86
The Public Modifier
  • Variables declared (or methods defined) using
    the Public modifier, can be accessed anywhere in
    a program or class.

87
The Private Modifier
  • Variables declared (or methods defined) using
    the Private modifier, can only be accessed by a
    method defined in the same class.

88
Using Public and Private
  • In general, all instance variables are Private
    and all methods are Public.

89
private variables - public methods
  • There are a few exceptions. For example
    'helper' methods are usually private. See page
    267 (4th Ed) of the text book.

90
Information 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

91
Accessor Methods
  • An accessor method is a method that allows you
    to read or to set one or more instance variables.

92
A Class With Accessor Methods SpeciesFourthTry.ja
va
  • http//www.annedawson.net/SpeciesFourthTry.java
  • page 258 of 4th Ed textbook

93
Using an Accessor Method SpeciesFourthTryDemo.jav
a
  • http//www.annedawson.net/SpeciesFourthTryDemo.jav
    a
  • page 259 of 4th Ed textbook

94
Information 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

95
Abstract Data Types
  • An abstract data type (ADT) is a data type (a
    class) which exhibits information hiding and
    encapsulation.

96
When you write your own classes
  • make sure that each class is an abstract data
    type!

97
Implementing 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

98
A class which is an ADT
  • has two parts
  • interface
  • and
  • implementation

99
The 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.

100
A class which is an ADT
  • has two parts
  • interface
  • and
  • implementation

101
Implementation
  • The implementation is simply the code.

102
Information 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

103
Encapsulation
  • Encapsulation means that the data and
    functions relevant to an object, are stored
    together as a single item, and the details are
    hidden.

104
Information 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

105
Automatic 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.

106
javadoc
  • See
  • http//www.annedawson.net/javadoc.htm

107
Chapter 4
  • 4.1 Class and Method Definitions
  • 4.2 Information Hiding and Encapsulation
  • 4.3 Objects and Reference

108
Objects 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

109
Objects 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

110
Variables of a Class Type and Objects
  • A variable of a class type
  • is an object.

111
To create an object
  • Syntax
  • Classname objectname new Classname()
  • Examples
  • Animal dog new Animal()
  • Animal cat new Animal()

112
To 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.

115
To 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.

116
When 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.

117
Objects 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

118
The 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). . .

120
Differences 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
123
Differences 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

124
cat 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.

125
The 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.

126
The equals method
  • Always define your own equals method.

127
Objects 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

128
Defining an equals Method Species.java
  • http//www.annedawson.net/Species.java
  • page 277 of 4th Ed textbook

129
Demonstrating an equals Method
SpeciesEqualsDemo.java
  • http//www.annedawson.net/SpeciesEqualsDemo.java
  • page 278 of 4th Ed textbook

130
Objects 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

131
Parameters of a Class Type
  • Firstly, let's just remind ourselves of
    parameters of a primitive type...

132
Parameters 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)

133
The 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)

134
The 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)

135
Inside 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)

136
Call-By-Value
  • When primitive types are used as arguments to
    methods, it is known as.....

137
Parameters of a Class Type
  • Parameters of a class type behave very
    differently to parameters of a primitive type....

138
Parameters 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.

140
Call-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.
141
Objects 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

142
Comparing 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.

143
And 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)

144
This 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

145
End of Java_Classes_Ch04.ppt
146
  • Last updated Friday 12th September 2008, 707
    PT, AHD
Write a Comment
User Comments (0)
About PowerShow.com