lecture-23.ppt

Download Report

Transcript lecture-23.ppt

Instance methods
Method
We found that it's more appropriate to put these method
inside the BankAccount class
An ideal class
The BankAccount class is ideally suited to contain/store:
• Information about BankAccount ( instance variables)
• Operations on BankAccount variables ( method)
Remember that program = data + algorithm
New notation to invoke a method
Terminology
• A class method
Methods defined with the keyword static
• An instance method
Methods defined without the keyword static
Shadowing a instance variable (1)
• When the method has:
local/parameter variable = class/instance variable
• The class/instance variable can no longer accessible with
the short hand notation in that scope
“This” (1)
The Java compiler always assume that the type of
the variable this is:
“This” (2)
A variable name used inside a method:
• that matches the name of a local/parameter
variable refers to the local/parameter variable
• Otherwise:
it refers to a class variable or an instance variable
Shadowing a instance variable (2)
• Overcome the shadowing problem with instance variables:
Use the full name to access the instance variable:
Object-oriented programming
(OOP)
• An object is an entity with some state information and
a set of well-defined operations
• It can be used to represent something in the real world
• It can be used to organize information used inside a computer
program.
Implementing an object
• Represent the state information of the object accurately
with (instance) variables,
and
• Represent the operations on the object accurately
with (instance) methods
Copying an object (1)
• Both an object and an array are accessed through a reference
variable
Copying an object (2)
Copying an object (3)
Copying an object (4)
Classes with private variables (1)
• Security/correctness considerations in computer programming
Classes with private variables (2)
• If there exist complex relationships between different
instance variables, we must maintain the relationship correctly
• Granting unrestricted access to the instance variables can result
in incorrect changes and can give result in data inconsistency
Classes with private variables (3)
• public = there are no access restrictions to a variable or
method
Classes with private variables (4)
• private = access is restricted to the same class
Classes with private variables (5)