Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Compiled Lesson 4 - Object State and Method Behavior

1. The document discusses object state (instance variables) and behavior (methods) and how they relate. Objects contain instance variables and methods defined by their class. 2. Classes are used as blueprints to create multiple object instances. Each object gets its own copy of the non-static parts of its class, including instance variables and methods. 3. Static members are part of the class itself and are shared among all instances, while instance variables and methods are unique to each object instance.

Uploaded by

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

Compiled Lesson 4 - Object State and Method Behavior

1. The document discusses object state (instance variables) and behavior (methods) and how they relate. Objects contain instance variables and methods defined by their class. 2. Classes are used as blueprints to create multiple object instances. Each object gets its own copy of the non-static parts of its class, including instance variables and methods. 3. Static members are part of the class itself and are shared among all instances, while instance variables and methods are unique to each object instance.

Uploaded by

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

IT108 – Integrative Programming Technologies

Lesson 4 – Object state and method behaviour

ACTIVATING
LEARNING
PRIOR KNOWLEDGE
OBJECTIVES
In 3 to 5 sentences write what you know about
At the end of the module, the I.T. students will be methods?
able to:
__________________________________________
a. Know the how state (instance variables) __________________________________________
and behavior(methods) are related.
__________________________________________
b. Differentiate arguments from
parameters __________________________________________
c. Understand how objects behave based __________________________________________
from the state it receive. __________________________________________

TOPIC
OUTLINE
OBJECT, CLASSES,
1. Methods use object state INSTANCES
2. Method arguments and return types
3. Pass-by-value
Objects are closely related to classes. Class can
4. Getters and Setters
contain variables and methods (that is, subroutines).
5. Encapsulation Classes "describe" objects, or more exactly that the
non-static portions of classes describe objects. But
it's probably not very clear what this means. The
more usual terminology is to say that objects belong
to classes, but this might not be much clearer.
OVERVIEW (There is a real shortage of English words to
properly distinguish all the concepts involved. An
object certainly doesn't "belong" to a class in the
same way that a member variable "belongs" to a
Welcome to Java programming whether you are a class.) From the point of view of programming, it is
seasoned programmer or a complete novice, this more exact to say that classes are used to create
hand out is written to help you learn Java objects. A class is a kind of factory—or blueprint—
for constructing objects. The non-static parts of the
programming fast. Topics are carefully selected to
class specify, or describe, what variables and
give you a broad exposure to the fundamental methods the objects will contain. This is part of the
concepts of Java while not overwhelming you with explanation of how objects differ from classes:
information overload. Objects are created and destroyed as the program
runs, and there can be many objects with the same
This hand out will serve as a guide as we progress structure, if they are created using the same class.
through the class, but it can also be a valuable tool
when you are working on your own. Any class Consider a simple class whose job is to group
instruction is only as effective as the time and effort together a few static member variables. For
example, the following class could be used to store
you are willing to invest in it. I encourage you to information about the person who is using the
practice the activity given in this hand out. program:

Lesson 4 – Variable: Object state and Method behaviour | Page 1 of 9


variables called name and age. This is what it
means for the non-static parts of the class to be a
template for objects: Every object gets its own copy
of the non-static part of the class. We can visualize
the situation in the computer's memory after several
objects have been created like this:
In a program that uses this class, there is only one
copy of each of the variables UserData.name and Note that the static variable playerCount is part of
UserData.age. When the class is loaded into the
computer, there is a section of memory devoted to
the class, and that section of memory includes
space for the values of the variables name and age.
We can picture the class in memory as looking like
this:

the class, and there is only one copy. On the other


hand, every object contains a name and an age. An
An important point is that the static member object that is created from a class is called an
variables are part of the representation of the class instance of that class, and as the picture shows,
in memory. Their full names, UserData.name and every object "knows" which class was used to create
UserData.age, use the name of the class, since they it. I've shown class PlayerData as containing
are part of the class. When we use class UserData something called a "constructor;" the constructor is a
to represent the user of the program, there can only subroutine that creates objects.
be one user, since we only have memory space to
store data about one user. Note that the class, Now there can be many "players," because we can
UserData, and the variables it contains exist as long make new objects to represent new players on
as the program runs. (That is essentially what it demand. A program might use the PlayerData class
means to be "static.") Now, consider a similar class to store information about multiple players in a
that includes some non-static variables: game. Each player has a name and an age. When a
player joins the game, a new PlayerData object can
be created to represent that player. If a player leaves
the game, the PlayerData object that represents that
player can be destroyed. A system of objects in the
program is being used to dynamically model what is
happening in the game. You can't do this with static
variables! "Dynamic" is the opposite of "static."

An object that is created using a class is said to be


I've also included a static variable in the PlayerData an instance of that class. We will sometimes say that
class. Here, the static variable playerCount is stored the object belongs to the class. The variables that
as part of the representation of the class in memory. the object contains are called instance variables.
Its full name is PlayerData.playerCount, and there is The methods (that is, subroutines) that the object
only one of it, which exists as long as the program contains are called instance methods. For example,
runs. However, the other two variables in the class if the PlayerData class, as defined above, is used to
definition are non-static. There is no such variable as create an object, then that object is an instance of
PlayerData.name or PlayerData.age, since non- the PlayerData class, and name and age are
static variables do not become part of the class instance variables in the object.
itself. But the PlayerData class can be used to
create objects. There can be many objects created My examples here don't include any methods, but
using the class, and each one will have its own methods work similarly to variables. Static methods

Lesson 4 – Variable: Object state and Method behaviour | Page 2 of 9


are part of the class; non-static, or instance, that is an instance of the Student class will include
methods become part of objects created from the instance variables named name, test1, test2, and
class. It's not literally true that each object contains test3, and it will include an instance method named
its own copy of the actual compiled code for an getAverage(). The names and test grades in
instance method. But logically an instance method is different objects will generally have different values.
part of the object, and I will continue to say that the When called for a particular student, the method
object "contains" the instance method. getAverage() will compute an average using that
student's test grades. Different students can have
Note that you should distinguish between the source different averages. (Again, this is what it means to
code for the class, and the class itself (in memory). say that an instance method belongs to an individual
The source code determines both the class and the object, not to the class.)
objects that are created from that class. The "static"
definitions in the source code specify the things that In Java, a class is a type, similar to the built-in types
are part of the class itself (in the computer's such as int and boolean. So, a class name can be
memory), whereas the non-static definitions in the used to specify the type of a variable in a declaration
source code specify things that will become part of statement, or the type of a formal parameter, or the
every instance object that is created from the class. return type of a function. For example, a program
By the way, static member variables and static could define a variable named std of type Student
member subroutines in a class are sometimes called with the statement
class variables and class methods, since they
belong to the class itself, rather than to instances of
that class.

As you can see, the static and the non-static


portions of a class are very different things and However, declaring a variable does not create an
serve very different purposes. Many classes contain object! This is an important point, which is related to
only static members, or only non-static, and we will this Very Important Fact:
see only a few examples of classes that contain a
mixture of the two.

FUNDAMENTALS
You should think of objects as floating around
OF OBJECTS independently in the computer's memory. In fact,
there is a special portion of memory called the heap
where objects live. Instead of holding an object itself,
So far, I've been talking mostly in generalities, and I a variable holds the information necessary to find the
haven't given you much of an idea about what you object in memory. This information is called a
have to put in a program if you want to work with reference or pointer to the object. In effect, a
objects. Let's look at a specific example to see how reference to an object is the address of the memory
it works. Consider this extremely simplified version location where the object is stored. When you use a
of a Student class, which could be used to store variable of object type, the computer uses the
information about students taking a course: reference in the variable to find the actual object.

In a program, objects are created using an operator


called new, which creates an object and returns a
reference to that object. (In fact, the new operator
calls a special subroutine called a "constructor" in
the class.) For example, assuming that std is a
variable of type Student, declared as above, the
assignment statement

None of the members of this class are declared to


be static, so the class exists only for creating
objects. This class definition says that any object

Lesson 4 – Variable: Object state and Method behaviour | Page 3 of 9


would create a new object which is an instance of If the value of a variable is null, then it is, of course,
the class Student, and it would store a reference to illegal to refer to instance variables or instance
that object in the variable std. The value of the methods through that variable—since there is no
variable is a reference, or pointer, to the object. The object, and hence no instance variables to refer to!
object itself is somewhere in the heap. It is not quite For example, if the value of the variable std is null,
true, then, to say that the object is the "value of the then it would be illegal to refer to std.test1. If your
variable std" (though sometimes it is hard to avoid program attempts to use a null pointer illegally in this
using this terminology). It is certainly not at all true to way, the result is an error called a null pointer
say that the object is "stored in the variable std." The exception. When this happens while the program is
proper terminology is that "the variable std refers to running, an exception of type NullPointerException is
or points to the object," and I will try to stick to that thrown.
terminology as much as possible. If I ever say
something like "std is an object," you should read it Let's look at a sequence of statements that work
as meaning "std is a variable that refers to an with objects:
object."

So, suppose that the variable std refers to an object


that is an instance of class Student. That object
contains instance variables name, test1, test2, and
test3. These instance variables can be referred to as
std.name, std.test1, std.test2, and std.test3. This
follows the usual naming convention that when B is
part of A, then the full name of B is A.B. For
example, a program might include the lines.

This would output the name and test grades from the
object to which std refers. Similarly, std can be used
to call the getAverage() instance method in the
object by saying std.getAverage(). To print out the After the computer executes these statements, the
student's average, you could say:

More generally, you could use std.name any place


where a variable of type String is legal. You can use
it in expressions. You can assign a value to it. You
can even use it to call subroutines from the String
class. For example, std.name.length() is the number
of characters in the student's name.

It is possible for a variable like std, whose type is


given by a class, to refer to no object at all. We say
in this case that std holds a null pointer or null
reference. The null pointer is written in Java as
"null". You can store a null reference in the variable
std by saying.
situation in the computer's memory looks like this:

In this picture, when a variable contains a reference


to an object, the value of that variable is shown as
an arrow pointing to the object. Note, by the way,

Lesson 4 – Variable: Object state and Method behaviour | Page 4 of 9


that the Strings are objects! The variable std3, with a a variable of type String, and that it refers to the
value of null, doesn't point anywhere. The arrows string "Hello". Then would the test greeting ==
from std1 and std2 both point to the same object. "Hello" be true? Well, maybe, maybe not. The
This illustrates a Very Important Point: variable greeting and the String literal "Hello" each
refer to a string that contains the characters H-e-l-l-
o. But the strings could still be different objects, that
just happen to contain the same characters; in that
case, greeting == "Hello" would be false. The
function greeting.equals("Hello") tests whether
greeting and "Hello" contain the same characters,
which is almost certainly the question you want to
ask. The expression greeting == "Hello" tests
When the assignment "std2 = std1;" was executed, whether greeting and "Hello" contain the same
no new object was created. Instead, std2 was set to characters stored in the same memory location. (Of
refer to the very same object that std1 refers to. This course, a String variable such as greeting can also
is to be expected, since the assignment statement contain the special value null, and it would make
just copies the value that is stored in std1 into std2, sense to use the == operator to test whether
and that value is a pointer, not an object. But this "greeting == null".)
has some consequences that might be surprising.
For example, std1.name and std2.name are two
different names for the same variable, namely the The fact that variables hold references to objects,
instance variable in the object that both std1 and not objects themselves, has a couple of other
std2 refer to. After the string "Mary Jones" is consequences that you should be aware of. They
assigned to the variable std1.name, it is also true follow logically, if you just keep in mind the basic fact
that the value of std2.name is "Mary Jones". There is that the object is not stored in the variable. The
a potential for a lot of confusion here, but you can object is somewhere else; the variable points to it.
help protect yourself from it if you keep telling
yourself, "The object is not in the variable. The Suppose that a variable that refers to an object is
variable just holds a pointer to the object." declared to be final. This means that the value
stored in the variable can never be changed, once
You can test objects for equality and inequality using the variable has been initialized. The value stored in
the operators == and !=, but here again, the the variable is a reference to the object. So the
semantics are different from what you are used to. variable will continue to refer to the same object as
When you make a test "if (std1 == std2)", you are long as the variable exists. However, this does not
testing whether the values stored in std1 and std2 prevent the data in the object from changing. The
are the same. But the values that you are comparing variable is final, not the object. It's perfectly legal to
are references to objects; they are not objects. So, say
you are testing whether std1 and std2 refer to the
same object, that is, whether they point to the same
location in memory. This is fine, if it's what you want
to do. But sometimes, what you want to check is
whether the instance variables in the objects have
the same values. To do that, you would need to ask
whether "std1.test1 == std2.test1 && std1.test2 ==
std2.test2 && std1.test3 == std2.test3 && Next, suppose that obj is a variable that refers to an
std1.name.equals(std2.name)". object. Let's consider what happens when obj is
passed as an actual parameter to a subroutine. The
I've remarked previously that Strings are objects, value of obj is assigned to a formal parameter in the
and I've shown the strings "Mary Jones" and "John subroutine, and the subroutine is executed. The
Smith" as objects in the above illustration. (Strings subroutine has no power to change the value stored
are special objects, treated by Java in a special way, in the variable, obj. It only has a copy of that value.
and I haven't attempted to show the actual internal However, the value is a reference to an object. Since
structure of the String objects.) Since strings are the subroutine has a reference to the object, it can
objects, a variable of type String can only hold a change the data stored in the object. After the
reference to a string, not the string itself. This subroutine ends, obj still points to the same object,
explains why using the == operator to test strings for but the data stored in the object might have
equality is not a good idea. Suppose that greeting is

Lesson 4 – Variable: Object state and Method behaviour | Page 5 of 9


changed. Suppose x is a variable of type int and stu gives you complete control over what can be done
is a variable of type Student. Compare: with the variable. Even if the variable itself is private,
you can allow other classes to find out what its value
is by providing a public accessor method that returns
the value of the variable. For example, if your class
contains a private member variable, title, of type
String, you can provide a method

that returns the value of title. By convention, the


name of an accessor method for a variable is
obtained by capitalizing the name of variable and
adding "get" in front of the name. So, for the variable
title, we get an accessor method named "get" +
"Title", or getTitle(). Because of this naming
convention, accessor methods are more often
referred to as getter methods. A getter method
provides "read access" to a variable. (Sometimes for
boolean variables, "is" is used in place of "get". For
example, a getter for a boolean member variable
named done might be called isDone().)

You might also want to allow "write access" to a


private variable. That is, you might want to make it
possible for other classes to specify a new value for
the variable. This is done with a setter method. (If
you don't like simple, Anglo-Saxon words, you can
use the fancier term mutator method.) The name of
a setter method should consist of "set" followed by a
capitalized copy of the variable's name, and it should
have a parameter with the same type as the
variable. A setter method for the variable title could
be written.

It is actually very common to provide both a getter


GETTERS AND and a setter method for a private member variable.
Since this allows other classes both to see and to
SETTERS change the value of the variable, you might wonder

When writing new classes, it's a good idea to pay


attention to the issue of access control. Recall that
making a member of a class public makes it why not just make the variable public? The reason is
accessible from anywhere, including from other that getters and setters are not restricted to simply
classes. On the other hand, a private member can reading and writing the variable's value. In fact, they
only be used in the class where it is defined. can take any action at all. For example, a getter
method might keep track of the number of times that
In the opinion of many programmers, almost all the variable has been accessed:
member variables should be declared private. This

Lesson 4 – Variable: Object state and Method behaviour | Page 6 of 9


The meaning of Encapsulation, is to make sure that
"sensitive" data is hidden from users. To achieve
this, you must:

 declare class variables/attributes as


And a setter method might check that the value that private
is being assigned to the variable is legal:  provide public get and set methods to
access and update the value of a private
variable
Even if you can't think of any extra chores to do in a
getter or setter method, you might change your mind
in the future when you redesign and improve your Get and Set
class. If you've used a getter and setter from the You learned from the previous chapter that private
beginning, you can make the modification to your variables can only be accessed within the same
class without affecting any of the classes that use class (an outside class has no access to it).
your class. The private member variable is not part However, it is possible to access them if we provide
of the public interface of your class; only the public public get and set methods.
getter and setter methods are, and you are free to
change their implementations without changing the The get method returns the variable value, and the
public interface of your class. If you haven't used get set method sets the value.
and set from the beginning, you'll have to contact
everyone who uses your class and tell them, "Sorry Syntax for both is that they start with either get or
people, you'll have to track down every use that set, followed by the name of the variable, with the
you've made of this variable and change your code first letter in upper case:
to use my new get and set methods instead."

A couple of final notes: Some advanced aspects of


Java rely on the naming convention for getter and
setter methods, so it's a good idea to follow the
convention rigorously. And though I've been talking
about using getter and setter methods for a variable,
you can define get and set methods even if there is
no variable. A getter and/or setter method defines a
property of the class that might or might not
correspond to a variable. For example, if a class
includes a public void instance method with
signature setValue(double), then the class
has a "property" named value of type
double, and it has this property whether or
not the class has a member variable
named value. Example explained

The get method returns the value of the variable


name.
ENCAPSULATION The set method takes a parameter (newName) and
assigns it to the name variable. The this keyword is
used to refer to the current object.

Lesson 4 – Variable: Object state and Method behaviour | Page 7 of 9


However, as the name variable is declared as
private, we cannot access it from outside this class:

1.
If the variable was declared as public, we would
expect the following output:
2.
However, as we try to access a private variable, we
get an error:

3. Fix the program called SomethingIsWrong


shown in Question 1.
Instead, we use the getName() and setName()
methods to access and update the variable:

SUMMARY
Let us see if you can remember the main points
raised in this lesson. Below is a summary of these
points:

 Encapsulation in Java is a mechanism of


wrapping the data (variables) and code
acting on the data (methods) together as a
single unit. ... Declare the variables of a
class as private. Provide public setter and
getter methods to modify and view the
variables values.

LEARNING
 Getter and setter are two conventional
ACTIVITY
methods that are used for retrieving and
updating value of a variable. ... And a getter
Objective: To evaluate and check proper java is a method that reads value of a variable.
coding. Getter and setter are also known as
accessor and mutator in Java.
Task: Find out what is wrong in the following
program and explain why.

Lesson 4 – Variable: Object state and Method behaviour | Page 8 of 9


 A setter is a method that updates the value
of a variable. It is also known as accessor
and mutator in Java.

 A method is a block of code which only runs


when it is called. You can pass data, known
as parameters, into a method. Methods are
used to perform certain actions, and they are
also known as functions.

REFERENCES
 Wu.C.Thomas.2004. AN introduction to
Object-oriented Programming in Java

 D.S Malik.2007.Java Programming from


problem analysis to program design

 Luliana Cosmia.2018.Java for absolute


Beginners.

 Jamie Chan.2016. Learn Java in one day


and learn it well.

 Kathy Sierra & Bert Bates (2005). Head


First Java,2nd Edition. ISBN 978-0-596-
00920-5 00920-5 Retrieved from
https://tinyurl.com/y3o97a9a

 Joyce Farrel (2019). Java Programming


ISBN: ISBN-13 978-1-337-39707-0
Retrieved from https://tinyurl.com/y2geqjut

Compiled by:

(Signed)
MARIA CLARIZA M. ESTOESTA
Professor, College of Information and Technology
Education

(Signed)
JOHANNS B. RABAGO
LORIE JELENE MILLON-PARAGAS
Professor

Lesson 4 – Variable: Object state and Method behaviour | Page 9 of 9

You might also like