methods - SEAS - University of Pennsylvania

Download Report

Transcript methods - SEAS - University of Pennsylvania

Intro to Computer Science
Class #3
Formalizing Variables, Methods and Inheritance
Instructor: Ms. Catherine Stocker
Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault
University of Pennsylvania
6 February 2008
Today’s Agenda
•
•
•
•
•
•
Discussion (Reaction paper and BotPlay)
Javadocs
Variables
Methods
Objects
Intro to Inheritance
• BetterBot
Discussion
Let’s talk about the reaction paper and what
you discovered in BotPlay.
Reminder:
What to do if you’re stuck…
1)
Try things out! Don’t be scared of the computer. (Just
make sure to have a backup copy of your work!)
2)
Check out the resources page
3)
Post to the bulletin board! (you can get to it now =)
4)
Come talk to us (before/after class).
5)
Email me [email protected]
Reminder:
What is Java?
• From someone who didn’t know last week...
• A high-level, object-oriented, programming language
• Language:
– A way for people to communicate…with computers
– Made of vocabulary and syntax (rules for how to arrange the
vocabulary)…which you’ll learn in this class
• High-level: High-level of abstraction
– Abstraction: Hiding unimportant details…like what type of
computer we’re communicating with.
• Object-Oriented: Thinking about your program as a
collection of objects that have a state and a behavior.
Reminder:
Other Objects
•
Abstract away the unnecessary details – only keep the important (relevant to the
program) ones in the state.
Baseball Player
• Program1: Keep track of baseball stats
– Object: Baseball Player
– State: name, G, AB, R, H, HR, on base, at bat
– Behavior: run, walk, hit ball, slide, batting
name
Ryan H
R
255
onBase
3
G
410
H
425
atBat
no
AB
1461
HR
128
RBI
353
• Program2: Simulate how athletes lifestyles affect their popularity
with fans, salary and injury rate
– Object: Athlete
– State: name, sport, salary, days injured, popularity
– Behavior: negotiate contract, party, complain, retire
Athlete
name
Ryan H
daysInjured
sport
25
baseball
popularity
salary
900,000
high
•
Reminder:
How Do We Translate What We’ve Talked About Into Java?
class Athlete {
String name ;
String sport;
int salary;
int daysInjured;
String popularity;
Athlete(String n, String s) {
name = n;
sport = s;
salary = 0;
daysInjured = 0;
popularity = “average”;
}
class (object blueprint)
instance variables (hold
the state)
constructor.
•Creates the object
•Sets the starting state
void negotiateContract(int newSalary) {
salary = newSalary;
}
void party() {
daysInjured = daysInjured + 10;
}
void complain() {
popularity = “low”;
}
void retire() {
salary = 0;
popularity = “high”;
}
methods
•modify the instance
variables (behaviors
changing the state)
•return the instance
variables (tell us about the
state)
void printStates() {
System.out.println(“name: “ + name + “, sport: “ + sport + “, salary: “ + salary + “, daysInjured: “ + daysInjured + “,
popularity”);
}
}
Summary of Last Week
• We learned about Java and objects and classes and methods
• But we didn’t discuss the formal rules…so what?
• There’s no room for interpretation when we communicate with
computers!
– “I wnt to. class Yesterday,” – Ok for humans
– String yesterday = “Tuesday”;
Yesterday = “Monday”,
• what’s wrong with this code?
• Computers are case-sensitive
• ‘;’ ≠ ‘.’ ≠ ‘,’
• Today we’re going to discuss the formal definition of methods
Summary of Last Week
• We learned about Java, objects, classes, variables and methods
• But we didn’t discuss the formal rules…so what?
• There’s no room for interpretation when we communicate with
computers!
– “I wnt to. class Yesterday,” – Ok for humans
– String yesterday = “Tuesday”;
Yesterday = “Monday”,
•
•
•
•
what’s wrong with this code?
Computers are case-sensitive
‘;’ ≠ ‘.’ ≠ ‘,’
Computers do EXACTLY what you tell them. Even if you’re wrong!
• Today we’re going to formalize all of that!
Variables
•
Used to store and retrieve a value in/from memory
– ex. int x = 5;
int y = x*2;
•
Must be declared once before being used.
x
5
y
10
– Why? So the computer knows…
• How much space in memory is needed to hold it.
• What operations are allowed to be performed on it.
– 1+2? .5+37.5? true+false?
•
Definitions of the different ways to use variables:
5
“Hello”
10
x
myStringVar
y
– Instance variables – Store the state of each object.
• Declared at top of class.
• Scope: Accessible to the entire object.
– Local variables – Stores the temporary state of a method.
• Declared at top of method.
• Scope: Accessible to the entire method.
– Parameters – Passed to methods.
• Scope: Accessible to the entire method.
– Class variables – We’ll talk about later in the course.
Snapshot of a modified Athlete class
•
class Athlete {
String name ;
String sport;
int salary;
int daysInjured;
String popularity;
Athlete(String n, String s) {
name = n;
sport = s;
salary = 0;
daysInjured = 0;
popularity = “average”;
}
void negotiateContract(int newSalary) {
int bargain = 2;
salary = newSalary/bargain;
}
...//the rest of the methods
}
instance variables
parameters
local variable
Structure of a Variable Declaration
• type_of_variable variable_name;
• type_of_variable:
– Primitive types:
• Defined by Java, part of its “vocabulary” already [keywords]
• Acted on with operators [+,-,/,*,=,==,<,>,etc]
• Only 8:
–
–
–
–
–
int - whole number (-2,147,483,648,…, -2, -1, 0, 1, 2,…2,147,483,647)
double - fractional/floating-point number (-2.0,-1.9,-1.89,0.34123,12.3)
char – a single character enclosed by single quotes (‘a’, ‘$’, ‘1’)
boolean - truth value (true, false)
Also: byte, short, long, float, but we won’t use those.
– Non-primitive types:
• Any class defined by us (or Java) becomes a new type
– We can declare variables of that type
– String – Anything enclosed by double quotes (“a”, “”, “1”, “Hello there friend!”)
» Special case of non-primitive: defined by java, keyword, acted on by an
operator (+) but is actually an object.
• Acted on by methods [variable_name.method_name(parameters)]
Structure of a Variable Declaration
• type_of_variable variable_name;
• type_of_variable:
– Primitive types:
• Defined by Java, part of it’s “vocabulary” already [ keywords]
• Acted on with operators [+,-,/,*,=,==,<,>,etc]
• Only 8:
–
–
–
–
–
int - whole number (-2,147,483,648,…, -2, -1, 0, 1, 2,…2,147,483,647)
double - fractional/floating-point number (-2.0,-1.9,-1.89,0.34123,12.3)
char – a single character enclosed by single quotes (‘a’, ‘$’, ‘1’)
boolean - truth value (true, false)
Also: byte, short, long, float, but we won’t use those.
– Non-primitive types:
• Any class defined by us (or Java) becomes a new type
– We can declare variables of that type
– String – Anything enclosed by double quotes (“a”, “”, “1”, “Hello there friend!”)
» Special case of non-primitive: defined by Java, keyword, acted on by an
operator (+) but is actually an object.
• Acted on by methods [variable_name.method_name(parameters)]
Structure of a Variable Declaration
• type_of_variable variable_name;
• type_of_variable:
– Primitive types:
• Defined by Java, part of it’s “vocabulary” already [ keywords]
• Acted on with operators [+,-,/,*,=,==,<,>,etc]
• Only 8:
–
–
–
–
–
int - whole number (-2,147,483,648,…, -2, -1, 0, 1, 2,…2,147,483,647)
double - fractional/floating-point number (-2.0,-1.9,-1.89,0.34123,12.3)
char – a single character enclosed by single quotes (‘a’, ‘$’, ‘1’)
boolean - truth value (true, false)
Also: byte, short, long, float, but we won’t use those.
– Non-primitive types:
• Any class defined by us (or Java) becomes a new type
– We can declare variables of that type
– String – Anything enclosed by double quotes (“a”, “”, “1”, “Hello there friend!”)
» Special case of non-primitive: defined by Java, keyword, acted on by an
operator (+) but is actually an object.
• Acted on by methods [variable_name.method_name(parameters)]
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Declaration
• type_of_variable variable_name;
• variable_name: (Almost anything you want)
– Should be descriptive!
• ex. salary, name, etc
– Can’t use keywords
• What keywords do we know already?
• General rule: if it turns a different color when you write it in drJava, it’s a
keyword
– Case-sensitive (hello ≠ Hello)
– Must begin with:
•
A letter (also $ or _ but don’t use those)
Followed by any combination of:
•
•
•
•
Letters
Numbers
$
_
– No spaces allowed: write the 1st word lowercase, all other words capital
• myVariable, yourVariable, thisIsAReallyLongVariable
Structure of a Variable Assignment
•
variable_name = data_value;
•
Examples:
–
–
•
–
- String profession;
profession = “grad
student”;
int myAge;
myAge = 24.5;
Will cause an error…why?
A specific case: variable_name = new constructor(parameter_list);
–
–
•
- char firstLetter;
firstLetter = ‘a’;
- boolean
inClass;
inClass = true;
What’s wrong with this:
–
•
int myAge;
myAge=24;
double pi;
pi = 3.14;
Where have we seen that?
We’ll talk about this more in a minute
Putting it all together: type_of_variable variable_name = data_value;
–
–
We can declare alone or assign alone or do both at once.
double pi = 3.14;
char firstLetter = ‘a’;
Review
• What are…
–
–
–
–
Instance variables?
Local variables?
Parameters?
Primitive types?
• How do you..
– Declare a variable?
• What’s wrong with these variables:
–
–
–
–
–
–
Hello
xyz
Myveryfirstvariable
this is a variable?
1Variable
variable1
Methods
•
•
modifier return_type method_name(parameter_list) {
method_body
}
modifier:
–
–
•
What can “see” it, we’ll discuss more on this later.
For now, assume all methods are public.
Remember types? Any of these + void.
The data type of the value returned by the method, void if returning nothing.
Same rules as variable names
Methods represent behaviors, so generally named with a verb (remember the Athlete class:
negotiateSalary, retire, party, complain, etc)
parameter_list:
–
–
•
}
method_name:
–
–
•
daysInjured = daysInjured + 10;
return_type:
–
–
•
public void party() {
Discussed before: Just a special case of variables
This section can be empty or contain a list of parameters preceded by their data type and
separated by commas
method_body:
–
May include: Declaration of local variables, manipulation of variables (instance, local or
parameters), return statement (returns data of type return_type).
Snapshot of a modified Athlete class
• public class Athlete {
int salary;
….
return_type (void so no return statement)
method_name
modifier
parameter_list
public void negotiateContract ( int newSalary ) {
int bargain = 2;
method_body
salary = newSalary/bargain;
}
return_type
parameter_list (empty)
modifier
method_name
public int getSalary ( ) {
return salary;
}
...//the rest of the methods
}
method_body
(returns an int)
The Constructor
•
modifier class_name(parameter_list) {
constructor_body
}
•
Creates the object from the class “blueprint”.
•
Looks like a method, with some differences:
public Athlete(String n, String s) {
name = n;
sport = s;
salary = 0;
daysInjured = 0;
popularity = “average”;
}
– No return_type.
– Its name is the same as the class.
•
Sets up the initial state.
•
Remember variable declaration and assignment?
– Remember any class you create becomes a non-primitive type?
– Variable declaration and assignment for non-primitive types:
type_of_variable variable_name = new constructor(parameter_list);
ex. Athlete a1 = new Athlete(“Ryan”, “Baseball Player”); //call constructor
int initialSalary = a1.getSalary();
//call method
Question
• We found some ways the Bots were deficient…
• How do we make them better?
– Add to the code?
• What if we can’t get to the code?
• What if we want to keep this Bot definition too?
– Copy and Paste?
• Waste of time and space (memory).
• Inheritance…
Introduction to Inheritance
• modifier class subclass_name extends superclass_name {
class_body
}
• A subclass (class that’s inheriting) inherits the methods
and instance variables of the superclass.
• Constructor of superclass not inherited, so must call
super(parameters); within the subclass constructor.
• Most common way this is done is : Object class
– All classes extend the object class
• More about this next week.
public class BetterBot extends Bot {
public BetterBot(BotWorld world){
super(world);
}
//additional methods
}
Now…
• Pennkeys!
– Memorize them!
– Go to the Bulletin Board to ask questions.
– Submit this week’s reaction paper
• BetterBot
(http://www.seas.upenn.edu/~cis1xx/projects/Botworld/betterbot/assignment.html)
Later…
• Using inheritance, extend either the class you
wrote last week or BetterBot. Include at least 2
new instance variables and 2 new methods in
your subclass.
• Write down something you were confused about
from class and a short explanation about what
confused you (1-3 sentences).
• Ask questions on the bulletin board.
• Submit using the link on the webpage