Intro to Computer Science Class #3 Formalizing Variables, Methods and Inheritance Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Slides:



Advertisements
Similar presentations
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Advertisements

Written by: Dr. JJ Shepherd
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
Road Map Introduction to object oriented programming. Classes
Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
Intro to Computer Science Class #2 Administrative Details and Introduction to Objects Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie,
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Lecture 2: Variables and Expressions Yoni Fridman 6/29/01 6/29/01.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CSE 115 Week 4 February 4 - 8, Monday Announcements Software installation fest Tuesday & Wednesday 4-7 in Baldy 21. Software installation fest Tuesday.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
1 CS1130 Spring 2011: David Gries & Walker White Transition to Object-Oriented Programming Assumes programming knowledge in a language like Matlab, C,
COMP More About Classes Yi Hong May 22, 2015.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Introduction to Programming Writing Java Beginning Java Programs.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Unit 3: Java Data Types Math class and String class.
The Java Programming Language
CIT 590 Intro to Programming First lecture on Java.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Primitive Variables.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
Elements of a Java Program Bina Ramamurthy SUNY at Buffalo.
PHY 107 – Programming For Science. Announcements  Slides, activities, & solutions always posted to D2L  Note-taking versions before class, for those.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Variables, Primitives, and Objects A Visual Learner’s Guide.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
Introduction to Programming Writing Java Beginning Java Programs.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CHAPTER # 2 Part 2 PROGRAMS AND DATA 1 st semster King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
Working With Objects Tonga Institute of Higher Education.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Intro to Computer Science Arrays Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault University of.
Python Let’s get started!.
CPS120: Introduction to Computer Science Variables and Constants.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
1 09/03/04CS150 Introduction to Computer Science 1 What Data Do We Have.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
OOP Basics Classes & Methods (c) IDMS/SQL News
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Coding – Week 2 Functions, Arrays, and Objects. Functions  Functions are not a new concept – you’ve been using them already.  void setup() {} and void.
A Sample Program #include using namespace std; int main(void) { cout
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Chapter # 2 Part 2 Programs And data
Information and Computer Sciences University of Hawaii, Manoa
User Interaction and Variables
Chapter 7 User-Defined Methods.
Programming Language Concepts (CIS 635)
Lesson 2: Building Blocks of Programming
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Chapter 2: Java Fundamentals
Recap Week 2 and 3.
Chapter # 2 Part 2 Programs And data
Object Oriented Programming in java
Variables and Constants
Classes and Methods 15-Aug-19.
Presentation transcript:

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 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) me

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. 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 R H HR onBase atBat RBI 3 no 353

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

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. –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? ? 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

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, ,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, ,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, ,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 1 st 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 1 st 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 1 st 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 1 st 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 1 st 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 1 st word lowercase, all other words capital myVariable, yourVariable, thisIsAReallyLongVariable

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”;

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. 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; }

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)

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”; }

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 (

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