0% found this document useful (0 votes)
10 views49 pages

Lecture4-Working With Objects-Part1

Uploaded by

rigop58682
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

Lecture4-Working With Objects-Part1

Uploaded by

rigop58682
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Advanced Programming

Fateme Moradpour
● Call methods: used on an instance of a class

samBot.turnRight();

● Define methods: give a class specific capabilities

public void turnLeft() {

// code to turn Robot left goes here

Working with Objects: Part 1 2


● Define methods that take in generic parameters (input) and have return values
(output); e.g., this Calculator’s method:
public int add(int x, int y) {
return x + y; // x, y are dummy (symbolic) variables
}

● Call such methods on instances of a class by providing specific arguments (actual


values for symbolic parameters)

myCalculator.add(5, 8);

● Remember the one-to-one correspondence rule: list of arguments must match list of
parameters in number, order, and types

Working with Objects: Part 1 3


● Recall that classes are just blueprints

● A class gives a basic definition of an object we want to model (one


or more instances of that class)

● It tells the properties and capabilities of that object

● You can create any class you want and invent any methods and
properties you choose for it!

Working with Objects: Part 1 4


The Robot
● Instantiation means building an class
instance from its class

• the capabilities of the instance are


defined through the class’s methods new Robot();
● Ex: new Robot(); creates an
instance of Robot by calling the
Robot class’ constructor (see instance
next slide)
Working with Objects: Part 1 5
public class Dog {
public Dog() {
● A constructor is a method that is
// this is the constructor!
called to create a new instance
}

● Let’s define one for the Dog class public void bark(int numTimes) {
// code for barking goes here
● Let’s also add methods for actions }
all Dogs know how to do like bark, public void eat() {
eat, and wag their tails // code for eating goes here
}
public void wagTail() {
// code for wagging tail goes here
}
Working with Objects: Part 1
} 6
public class Dog {

● Note constructors do not specify a public Dog() {


return type // this is the constructor!
● Name of constructor must exactly match }
name of class public void bark(int numTimes) {
● Now we can instantiate a Dog in some // code for barking goes here
method using the new keyword:
}
new Dog(); public void eat() {
// code for eating goes here
}
public void wagTail() {
// code for wagging tail goes here
}
Working with Objects: Part 1 7
}
● Storing values in variables
● Instances as parameters
● Variable reassignment
● Local variables vs. instance variables
● Delegation pattern and containment

Working with Objects: Part 1 8


9

Instances as parameters, Storing values in


variables,Values and References variables
● Once we create a Dog instance, we want to be able to give it commands by calling
methods on it!

● To do this, we need to name our Dog

● Can name an instance by storing it in a variable

Dog django = new Dog();

● In this case, django is the variable, and it stores a newly created instance of Dog
the variable name django is also known as an “identifier”

● Now we can call methods on django, a specific instance of Dog


i.e., django.wagTail();

Working with Objects: Part 1 10


● We can both declare and assign (i.e., initialize) a variable in a single statement, like:

Dog django = new Dog();


declaration Instantiation, followed by assignment using =

<type> <name> = <value>;

● The “=” operator assigns the instance of Dog that we created to the variable django. We
say “django gets a new Dog”

● Note: type of value must match declared type on left

● We can reassign a variable as many times as we like (example soon)


Working with Objects: Part 1 11
int favNumber = 9;
● A variable stores information as either: favNumber
 a value of a primitive (aka base) type (like int or float) 9
 a reference to an instance (like an instance of Dog) of an arbitrary type
stored elsewhere in memory Dog django = new Dog();
• we symbolize a reference with an arrow django

● Think of the variable like a box; storing a value or reference is like putting
something into the box

● Primitives have a predictable memory size, while instances of classes vary in


size. Thus, Java simplifies memory management by having a fixed size
reference to an instance elsewhere in memory

 “one level of indirection”


(somewhere else in memory)
Working with Objects: Part 1 12
public class PetShop {

//constructor
● Let’s define a new class PetShop which has a
public PetShop() {
testdjango() method
this.testdjango();
 don’t worry if the example seems a bit
}
contrived…
public void testdjango() {
● Whenever someone instantiates a PetShop, its Dog django = new Dog();
constructor is called, which calls testdjango() django.bark(5);

● Then testdjango() instantiates a Dog and tells it django.eat();

to bark, eat, and wag its tail (see definition of Dog django.wagTail();

for what these methods do) }


Working with Objects: Part 1 } 13
● Another example: can instantiate a public class MathStudent {
MathStudent and then call that
instance to perform a simple, fixed,
/* constructor elided */
calculation, called
performCalculation()
public void performCalculation() {
● First, instantiate a new Calculator
Calculator myCalc = new Calculator();
and store its reference in variable
int answer = myCalc.add(2, 6);
named myCalc
System.out.println(answer);
● Next, tell myCalc to add 2 to 6 and }
store result in variable named answer
/* add() method elided */
● Finally, use System.out.println to ...
print value of answer to the console! }
Working with Objects: Part 1 14
● Methods can take in not just DogGroomer
Dog
numbers but also instances as PetShop
parameters
public class DogGroomer {
● The DogGroomer class has a public DogGroomer() {
method groom()
// this is the constructor!
name of
● groom method needs to know } type/class specific
instance
which Dog to groom public void groom(Dog shaggyDog) {

// code that groom the fur of shaggyDog


● Method calling groom will have
to supply a specific instance of }

Dog }
Working with Objects: Part 1 15
DogGroomer

● Where to call the DogGroomer’s groom Dog PetShop

method? public class PetShop {

● Do this in the PetShop method public PetShop() {

testGroomer() this.testGroomer();

}
● PetShop’s call to testGroomer()
public void testGroomer() {
instantiates a Dog and a DogGroomer,
Dog django = new Dog();
then calls the DogGroomer to groom of
the Dog DogGroomer groomer = new DogGroomer();

groomer.groom(django);
● First two lines could be in either
}
order
Working with Objects: Part 1 } 16
Instances as Parameters (3/3): Flow of Control
public class App {
0. In App's main, a PetShop is instantiated public static void main(String[] args) {
(thereby calling PetShop's constructor). Then:
0. PetShop petSmart = new PetShop();

1. The PetShop in turn calls the testGroomer() }


helper method, which instantiates a Dog and }
stores a reference to it in the variable django Public class PetShop {

public PetShop(){
2. Next, it instantiates a DogGroomer and stores
a reference to it in the variable groomer this.testGroomer();

}
3. The groom method is called on groomer, public void testGroomer() {
passing in django as an argument; the groomer
1. Dog django = new Dog();
will think of it as shaggyDog, a synonym
2. DogGroomer groomer = new PetShop();

3. groomer.groom(django);

//exit method, django and groomer disappear


Working with Objects: Part 1 17
}}
DogGroomer
Dog PetShop

public class App {

• Memory (“system memory” aka RAM, not disk or public static void main(String[] args) {

PetShop petSmart = new PetShop();


other peripheral devices) is the hardware in
}
which computers store information during
}
computation
Public class PetShop {

• Think of memory as a list of slots; each slot holds public PetShop(){

information (e.g., an int variable, or a reference this.testGroomer();

}
to an instance of a class)
public void testGroomer() {
• Here, two references are stored in memory: one Dog django = new Dog();
to a Dog instance, and one to a DogGroomer DogGroomer groomer = new PetShop();

instance groomer.groom(django);

}
Working with Objects: Part 1 18
}
public class PetShop { public class DogGroomer {

public Petshop() { public DogGroomer() {


this.testGroomer(); // this is the constructor!
}
}
public void testGroomer() {
public void groom(Dog shaggyDog) {
Dog django = new Dog();

DogGroomer groom = new DogGroomer(); // code that groom the fur of shaggyDog

groom.groom(django); }
} }
}

Working with Objects: Part 1 Somewhere in memory... 19


public class PetShop { public class DogGroomer {

public Petshop() { public DogGroomer() {

this.testGroomer(); // this is the constructor!

} }

public void testGroomer() { public void groom(Dog shaggyDog) {

Dog django = new Dog(); // code that groom the fur of shaggyDog
DogGroomer groom = new DogGroomer(); }
groom.groom(django); }
}

Working with Objects: Part 1 Somewhere in memory... 20


public class PetShop { public class DogGroomer {

public Petshop() { public DogGroomer() {

this.testGroomer(); // this is the constructor!

} }
public void testGroomer() { public void groom(Dog shaggyDog) {
Dog django = new Dog(); // code that groom the fur of shaggyDog
DogGroomer groom = new DogGroomer();
}
groom.groom(django);
}
}

Working with Objects: Part 1 Somewhere in memory... 21


public class PetShop { public class DogGroomer {

public Petshop() { public DogGroomer() {

this.testGroomer(); // this is the constructor!

} }
public void testGroomer() { public void groom(Dog shaggyDog) {
Dog django = new Dog(); // code that groom the fur of shaggyDog
DogGroomer groom = new DogGroomer();
}
groom.groom(django);
}
}

Working with Objects: Part 1 Somewhere in memory... 22


public class PetShop { public class DogGroomer {

public Petshop() { public DogGroomer() {

this.testGroomer(); // this is the constructor!

} }
public void testGroomer() { public void groom(Dog shaggyDog) {
Dog django = new Dog(); // code that groom the fur of shaggyDog
DogGroomer groom = new DogGroomer();
}
groom.groom(django);
}
}

Working with Objects: Part 1 Somewhere in memory... 23


public class DogGroomer {
public class PetShop {
public DogGroomer() {
public Petshop() {
// this is the constructor!
this.testGroomer();
}
}
public void groom(Dog shaggyDog) {
public void testGroomer() {
// code that groom the fur of shaggyDog
Dog django = new Dog();
}
DogGroomer groomer = new DogGroomer();
}
groomer.groom(django);

Working with Objects: Part 1 Somewhere in memory... 24


25 ● VARIABLE REASSIGNMENT

Reassignment, Garbage Collection


public class PetShop {

/*This is the Constructor*/


● After giving a variable an initial
public PetShop(){
value or reference, we can
reassign it (make it refer to a this.testGroomer();

different instance) }

public void testGroomer() {


● What if we wanted our DogGroomer
to groom two different Dogs when Dog django = new Dog();
the PetShop opened? DogGroomer groomer = new DogGroomer();

groomer.groom(django);

Working with Objects: Part 1 } 26


public class PetShop {

/*This is the Constructor*/


● First, instantiate another Dog, and public PetShop(){
reassign variable django to point
this.testGroomer();
to it
}
● Now django no longer refers to
the first Dog instance we created, public void testGroomer() {

which was already groomed Dog django = new Dog();

● Then tell groomer to groom the DogGroomer groomer = new DogGroomer();


new Dog. It will also be known as groomer.groom(django);
shaggyDog inside the groom
django = new Dog(); // reassign django
method
groomer.groom(django);

}
Working with Objects: Part 1 27
}
● When we reassign a variable, we do not declare its type again,
Java remembers from first time
● Can reassign to a brand new instance (like in PetShop) or to an
already existing instance by using its identifier

Dog django = new Dog();


Dog scooby = new Dog();
django = scooby; // reassigns django to refer to the same Dog as scooby

● Now django and scooby refer to the same Dog, specifically the
one that was originally referenced by scooby
Working with Objects: Part 1 28
public class PetShop {

public PetShop(){

this.testGroomer();

public void testGroomer() {

DogGroomer groomer = new DogGroomer();

Dog django = new Dog();

groomer.groom(django);

django = new Dog();

groomer.groom(django);

29
public class PetShop {

public PetShop(){

this.testGroomer();

public void testGroomer() {

DogGroomer groomer = new DogGroomer();

Dog django = new Dog();

groomer.groom(django);

django = new Dog();

groomer.groom(django);

30
public class PetShop {

public PetShop(){

this.testGroomer();

public void testGroomer() {

DogGroomer groomer = new DogGroomer();

Dog django = new Dog();

groomer.groom(django);

django = new Dog();

groomer.groom(django);

31
public class PetShop {

public PetShop(){

this.testGroomer();

public void testGroomer() {

DogGroomer groomer = new DogGroomer();

Dog django = new Dog();

groomer.groom(django);

django = new Dog();

groomer.groom(django);

32
public class PetShop {

public PetShop(){

this.testGroomer();

public void testGroomer() {

DogGroomer groomer = new DogGroomer();

Dog django = new Dog();

groomer.groom(django);

django = new Dog();

groomer.groom(django);

33
● If an instance referred to by a variable goes out of
scope, we can no longer access it. Because we can’t
access the instance, it gets garbage collected
in garbage collection, the space that the instance took up in
memory is freed and the instance no longer exists

● Lose access to an instance when:


at the end of method execution, local variables created within
that method go out of scope
variables lose their reference to an instance during variable
reassignment

Working with Objects: Part 1 34


35
LOCAL VARIABLES VS. INSTANCE VARIABLES

Local variables, instance variables,


NullPointerExceptions
public class PetShop {
● All variables we’ve seen so far have
been local variables: variables public PetShop() {
declared inside a method local variables
this.testGroomer();

● Problem: the scope of a local variable }


(where it is known and can be public void testGroomer() {
accessed) is limited to its own Dog django = new Dog();
method—it cannot be accessed from DogGroomer groomer = new DogGroomer();
anywhere else groomer.groom(django);

same is true of method’s parameters }

Working with Objects: Part 1 36


}
public class PetShop {
● We created groomer and django in
public PetShop() {
our PetShop’s testGroomer method,
but as far as the rest of the class is this.testGroomer(); local variables
concerned, they don’t exist and
}
cannot be used
public void testGroomer() {
● Once the method is completely
executed, they’re gone :( Dog django = new Dog();

this is known as “Garbage DogGroomer groomer = new DogGroomer();


Collection” groomer.groom(django);

}
Working with Objects: Part 1 37
public class PetShop {
scope of groomer

● If you try to access a local variable outside of


public PetShop() {
its method, you’ll receive a “cannot find
DogGroomer groomer = new DogGroomer();
symbol” compilation error
this.cleanShop();

public void cleanShop() {


In Terminal after javac *.java:
//assume we’ve added a sweep method
PetShop.java:13: error: cannot find symbol
groomer.sweep();
//to DogGroomer
^
symbol: variable groomer
groomer.sweep();
location: class PetShop
}
Working with Objects: Part 1 } 38
● Local variables aren’t always what we want. We’d like every PetShop to come

with a DogGroomer who exists for as long as the PetShop exists

● That way, as long as the PetShop is in business, we’ll have our DogGroomer on

hand

● We accomplish this by storing the DogGroomer in an instance variable

Working with Objects: Part 1 39


● An instance variable models a property that all instances of a class have
its value can differ from instance to instance

● Instance variables are declared within a class, not within a single method, and
therefore are accessible from anywhere within the class, unlike local variables –
their scope is the entire class

● Instance variables and local variables are identical in terms of what they can
store—either can store a base type (like an int) or a reference to an instance of
some other class

Working with Objects: Part 1 40


● Methods model capabilities of a class (e.g., move, dance)

● All instances of same class have exact same methods


(capabilities) and the same properties

● BUT: the values of those properties can be different and


can differentiate one instance from other instances of the
same class

● We use instance variables to model these properties and


their values (e.g., the robot’s size, position, orientation,
color, …)

Working with Objects: Part 1 41


● All instances of a class have same set of properties, but
values of these properties will differ
● E.g., APStudents might have property “height”
for one student, the value of “height” is 5’2”. For another,
it’s 6’4”

● APStudent class would have an instance variable to


represent height
• all APStudents have a “height”, but the value stored
in instance variable would differ from instance to
instance

Working with Objects: Part 1 42


In general, variables that fall into one of these three categories should be instance
variables of the class rather than local variables within a method:
• attributes: simple descriptors of an instance, e.g., color, height, age, ...; the next
two categories encode relationships between objects.
• components: "parts" that make up an instance. If you are modeling a car, the
car's engine and doors will be used in multiple methods, so they should be
instance variables; ditto PetShop and its DogGroomer
• associations: a relationship between two instances in which one instance knows
about the other, but they are not necessarily part of each other. For example, the
instructor needs to know about TAs (more on this soon), but the instructor is not
a part of the TA class - they are peers.

• All methods in a class can access all its properties, to use them and/or change them

Working with Objects: Part 1 43


declaration
public class PetShop {
We’ve modified PetShop example to make our
private DogGroomer _groomer;
DogGroomer an instance variable for the benefit of
multiple methods initialization
Split up declaration and assignment of instance public PetShop() {
variable:
_groomer = new DogGroomer();
• declare instance variable at the top of the class
above the constructor, to notify Java compiler this.testGroomer();
• initialize the instance variable by assigning a }
value to it in the constructor
public void testGroomer() {
primary purpose of constructor is to initialize all
instance variables so each instance has a valid Dog django = new Dog();//local var
initial “state” at its “birth”; it typically should do
no other work _groomer.groom(django);
• state is the set of all values for all properties— }
local variables don’t hold properties; they are
“temporaries”. State typically varies over time }
Working with Objects: Part 1 44
access modifier

● Note we include the keyword public class PetShop {


private in declaration of our
instance variable private DogGroomer _groomer;

● private is an access modifier, public PetShop() {


_groomer = new DogGroomer();
just like public, which we’ve been
this.testGroomer();
using in our method declarations }

public void testGroomer() {


Dog django = new Dog();//local var
_groomer.groom(django);
}
//payGroomer() method elided
}
Working with Objects: Part 1 45
access modifier
● If declared as private, the method or
instance variable can only be accessed public class PetShop {
inside the class – their scope is the
entire class private DogGroomer _groomer;

● If declared as public, can be accessed


public PetShop() {
from anywhere – their scope can include _groomer = new DogGroomer();
multiple classes – very unsafe!
this.testGroomer();
● In AP, you’ll declare instance }
variables as private, with rare
exception! public void testGroomer() {
Dog django = new Dog();//local var
● Note that local variables don’t have _groomer.groom(django);
access modifiers – they always have the }
same scope (their own method) //payGroomer() method elided
}
Working with Objects: Part 1 46
public class PetShop {
● AP instance variable rules:
private DogGroomer _groomer;
● make all instance variables private so
they can only be accessed from within public PetShop() {
their own class! _groomer = new DogGroomer();
this.testGroomer();
● encapsulation for safety...your properties }
are your private business. We will also
show you safe ways of allowing other public void testGroomer() {
Dog django = new Dog();//local var
classes to have selective access to
_groomer.groom(django);
designated properties... stay tuned. }
//payGroomer() method elided
}

Working with Objects: Part 1 47


● What if you declare an instance
variable, but forget to initialize it? public class PetShop {
What if you don’t supply a private DogGroomer _groomer;
constructor and your instance public PetShop() {
variables are not initialized?
//oops! Forgot to initialize groomer
● The instance variable will assume this.testGroomer();
a “default value” }
o if it’s an int, it will be 0 public void testGroomer() {

o if it’s an instance, it will be null— a Dog django = new Dog();//local var


special value that means your
_groomer.groom(django);
variable is not referencing any
instance at the moment }
Working with Objects: Part 1 48
}
public class PetShop {

private DogGroomer _groomer;


● If a variable’s value is null and you try to public PetShop() {
give it a command, you’ll be rewarded
with a runtime error—you can’t call a //oops! Forgot to initialize groomer
method on “nothing”! this.testGroomer();
● groomer’s default value is null, so this }
particular error yields a
NullPointerException public void testGroomer() {

● When you run into one of these (we Dog django = new Dog(); //local var
promise, you will), make sure all instance _groomer.groom(django);
variables have been explicitly
initialized, preferably in the constructor, }
and no variables are initialized as null

} NullPointerException

Working with Objects: Part 1 49

You might also like