when a method returns, all its resources (local variables) go away
Procedural Programming
Design Principle:
Break a large task into smaller sub-tasks
write a method for each sub-task
Makes code better:
shows intent
easier to maintain (one error, one bug)
makes code easier to read/understand
Methods allow for encapsulation: write a single piece of code that can be used by many parts of a program.
Object Orientation
Idea: encapsulate code in objects
Create object instances
each instance is like its own program
Instances have internal state
instance variables
Instances are persistent
once an instance is created, it remains indefinitely
Instances can change internal state
instance methods are specific to each instance
Instances can interact
call methods on an instance
Object Oriented Design
A different way to conceptualize a program:
Think in terms of interacting objects
Advantages:
More conceptual structure
Better encapsulation
Separate interface from implementation
don’t need to understand how an object works (internally) to use the object
Note
Object orientation is a useful abstraction
It does not provide greater power or more functionality
It is a way to think about:
solving problems
writing code
designing software
An Object
Forget about programming for a moment
Describe the Clicker Counter
What Functionality Does it Offer?
How do You Interact With it?
What is its Internal State?
What Limitations Does it Have?
How Can We Represent it in Code?
We will define a Counter object!
Internal state:
store count as an int
Instance methods:
get count
increment counter
reset
Constructor
Code it together!
The Completed Object
public class Counter {
private int count;
// constructor defines how to initialize instance
public Counter () {
count = 0;
}
// getter method for count
public int getCount () {
return count;
}
// increment the counter
public void increment () {
count++;
}
// reset the counter
public void reset () {
count = 0;
}
}
How can we use the Counter?
Create an instance of the Counter class:
// create a Counter instance
Counter myCounter = new Counter();
// increment the counter: call instance method
myCounter.increment();
// print the current count
System.out.println("Current count: " + myCounter.getCount());
Why Make a Counter Class?
Couldn’t we have just used an int?
Reasons Counter is Preferable to int
Semantics. a Counter signals object is being used to count something
an int could signify anything!
Safety. a Counter restricts the operations
cannot do something accidentally that would mess up count
Separate implementation from interface.
can change implementation without affecting code that uses counter
can use Counter objects without knowledge of internal workings
Extensibility. can add functionality without affecting the code using Counter