Download presentation
Presentation is loading. Please wait.
Published byAllyson Lynch Modified over 8 years ago
1
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
2
Today’s Agenda Discussion (Reaction paper and BotPlay) Javadocs Variables Methods Objects Intro to Inheritance BetterBot
3
Discussion Let’s talk about the reaction paper and what you discovered in BotPlay.
4
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 pageresources page 3)Post to the bulletin board! (you can get to it now =)bulletin board 4)Come talk to us (before/after class). 5)Email me cstocker@seas.upenn.educstocker@seas.upenn.edu
5
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.
6
Reminder: Other Objects Abstract away the unnecessary details – only keep the important (relevant to the program) ones in the state. 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 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 sport baseball salary 900,000 daysInjured 25 popularity high Baseball Player name G AB Ryan H 410 1461 R H HR 255 425 128 onBase atBat RBI 3 no 353
7
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”; } void negotiateContract(int newSalary) { salary = newSalary; } void party() { daysInjured = daysInjured + 10; } void complain() { popularity = “low”; } void retire() { salary = 0; popularity = “high”; } void printStates() { System.out.println(“name: “ + name + “, sport: “ + sport + “, salary: “ + salary + “, daysInjured: “ + daysInjured + “, popularity”); } instance variables (hold the state) methods modify the instance variables (behaviors changing the state) return the instance variables (tell us about the state) class (object blueprint) constructor. Creates the object Sets the starting state
8
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
9
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!
10
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. –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: –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. x y 5 10 xy 5“Hello” myStringVar
11
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
12
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)]
13
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)]
14
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)]
15
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
16
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
17
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
18
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
19
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
20
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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable
21
Structure of a Variable Assignment variable_name = data_value; Examples: –int myAge; myAge=24; –double pi; pi = 3.14; What’s wrong with this: –int myAge; myAge = 24.5; –Will cause an error…why? A specific case: variable_name = new constructor(parameter_list); –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’; - char firstLetter; firstLetter = ‘a’; - boolean inClass; inClass = true; - String profession; profession = “grad student”;
22
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
23
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. return_type: –Remember types? Any of these + void. –The data type of the value returned by the method, void if returning nothing. method_name: –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: –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). public void party() { daysInjured = daysInjured + 10; }
24
Snapshot of a modified Athlete class public class Athlete { int salary; …. public void negotiateContract ( int newSalary ) { int bargain = 2; salary = newSalary/bargain; } public int getSalary ( ) { return salary; }...//the rest of the methods } method_body parameter_list method_name return_type (void so no return statement) modifier parameter_list (empty) method_namemodifier return_type method_body (returns an int)
25
The Constructor modifier class_name(parameter_list) { constructor_body } Creates the object from the class “blueprint”. Looks like a method, with some differences: –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 public Athlete(String n, String s) { name = n; sport = s; salary = 0; daysInjured = 0; popularity = “average”; }
26
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…
27
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 }
28
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)BetterBot
29
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.