CS 106A, Lecture 21 Classes - Stanford University

2y ago
36 Views
2 Downloads
815.59 KB
30 Pages
Last View : 6d ago
Last Download : 5m ago
Upload by : Julia Hutchens
Transcription

CS 106A, Lecture 21Classessuggested reading:Java Ch. 6This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others.

Plan for today Recap: HashMaps What’s Trending Classes Recap2

Recap: HashMaps3

Plan for today Recap: HashMaps What’s Trending Classes Recap4

Large Java ProgramsThere are some large programs written in Java!5

Defining New Variable TypesInbox DatabaseEmailEmail SenderUserLogin ManagerInbox6

What Is A Class?A class defines anew variable type.7

Why Is This Useful? A student registration system needs to store info aboutstudents, but Java has no Student variable type. A music synthesizer app might want to store informationabout different types of instruments, but Java has noInstrument variable type. An email program might have many emails that need to bestored, but Java has no Email variable type. Classes let you define new types of variables, which lets youdecompose your program code across different files.8

Classes Are Like BlueprintsiPod blueprint (class)state:current songvolumebattery lifebehavior:power on/offchange station/songchange volumechoose random songconstructsiPod (variable) #1iPod (variable) #2iPod (variable) #3state:song "1,000,000 Miles"volume 17battery life 2.5 hrsstate:song "Letting You"volume 9battery life 3.41 hrsstate:song "Discipline"volume 24battery life 1.8 hrsbehavior:power on/offchange station/songchange volumechoose random songbehavior:power on/offchange station/songchange volumechoose random songbehavior:power on/offchange station/songchange volumechoose random song9

What Is A Class?A class defines anew variable type.10

Creating A New ClassLet’s define a new variable type called BankAccountthat represents information about a single person’sbank account.A BankAccount:- contains the name of account holder- contains the balance- can deposit money- can withdraw money11

What if What if we could write a program like this:BankAccount nickAccount new Account.deposit(50);BankAccount rishiAccount new shiAccount.deposit(50);boolean success rishiAccount.withdraw(10);if (success) {println(“Rishi withdrew 10.”);}12

Creating A New Class1. What information is inside this newvariable type? These are its private instancevariables.13

Example: BankAccount// In file BankAccount.javapublic class BankAccount {// Step 1: the data inside a BankAccountprivate String name;private double balance;}Each BankAccount object has its own copyof all instance variables.14

Creating A New Class1. What information is inside this newvariable type? These are its instancevariables.2. What can this new variable type do?These are its public methods.15

What if What if we could write a program like this:BankAccount nickAccount new nt rishiAccount new shiAccount.deposit(50);boolean success rishiAccount.withdraw(10);if (success) {println(“Rishi withdrew 10.”);}16

Example: BankAccountpublic class BankAccount {// Step 1: the data inside a BankAccountprivate String name;private double balance;// Step 2: the things a BankAccount can dopublic void deposit(double amount) {balance amount;}public boolean withdraw(double amount) {if (balance amount) {balance - amount;return true;}return false;}}17

Defining Methods In ClassesMethods defined in classes can be calledon an instance of that class.When one of these methods executes,it can reference that object’s copy ofinstance a1name "Marty"balance 1.45deposit(amount) {balance amount;}ba2name "Mehran"balance 901000.00deposit(amount) {balance amount;}This means calling one of these methods on different objects hasdifferent effects.18

Getters and SettersInstance variables in a class should always be private. This is so onlythe object itself can modify them, and no-one else.To allow the client to reference them, we define public methods inthe class that set an instance variable’s value and get (return) aninstance variable’s value. These are commonly known as getters andsetters.account.setName(“Nick”);String accountName account.getName();Getters and setters prevent instance variables from being tamperedwith.19

Example: BankAccountpublic class BankAccount {private String name;private double balance;.public void setName(String newName) {if (newName.length() 0) {name newName;}}public String getName() {return name;}}20

Creating A New Class1. What information is inside this newvariable type? These are its instancevariables.2. What can this new variable type do?These are its public methods.3. How do you create a variable of this type?This is the constructor.21

ConstructorsGRect rect new GRect();GRect rect2 new GRect(50, 50);This is calling a special method! The GRect constructor.22

ConstructorsBankAccount ba1 new BankAccount();BankAccount ba2 new BankAccount(“Nick”, 50);The constructor is executed when a new object is created.23

Example: BankAccountpublic class BankAccount {// Step 1: the data inside a BankAccountprivate String name;private double balance;// Step 2: the things a BankAccount can do (omitted)// Step 3: how to create a BankAccountpublic BankAccount(String accountName, double startBalance) {name accountName;balance startBalance;}public BankAccount(String accountName) {name accountName;balance 0;}}24

Using ConstructorsBankAccount ba1 new BankAccount("Marty", 1.25);ba1name "Marty"balance 1.25BankAccount(nm, bal) {name nm;balance bal;}BankAccount ba2 new BankAccount("Mehran", 900000.00);ba2name "Mehran"balance 900000.00 When you call a constructor (with new):BankAccount(nm, bal) {name nm;balance bal;}– Java creates a new object of that class.– The constructor runs, on that new object.– The newly created object is returned to your program.25

Constructors constructor: Initializes the state of new objects as they are created.public ClassName(parameters) {statements;}– The constructor runs when the client says new ClassName(.);– no return type is specified; it "returns" the new object being created– If a class has no constructor, Java gives it a default constructor with noparameters that sets all fields to default values like 0 or null.26

Plan for today Recap: HashMaps What’s Trending Classes Recap27

What Is A Class?A class defines anew variable type.28

Creating A New Class1. What information is inside this newvariable type? These are its instancevariables.2. What can this new variable type do?These are its public methods.3. How do you create a variable of this type?This is the constructor.29

Recap Recap: HashMaps What’s Trending Classes RecapNext time: more classes30

iPod blueprint (class) state: current song volume battery life behavior: power on/off change station/song change volume choose random song iPod (variable) #1 state: song "1,000,000 Miles" volume 17 battery life 2.5 hrs behavior: power on/off change station/song change volume choose random song iPod (variable) #2 state: song "Letting You .

Related Documents:

Introduction of Chemical Reaction Engineering Introduction about Chemical Engineering 0:31:15 0:31:09. Lecture 14 Lecture 15 Lecture 16 Lecture 17 Lecture 18 Lecture 19 Lecture 20 Lecture 21 Lecture 22 Lecture 23 Lecture 24 Lecture 25 Lecture 26 Lecture 27 Lecture 28 Lecture

Lecture 1: A Beginner's Guide Lecture 2: Introduction to Programming Lecture 3: Introduction to C, structure of C programming Lecture 4: Elements of C Lecture 5: Variables, Statements, Expressions Lecture 6: Input-Output in C Lecture 7: Formatted Input-Output Lecture 8: Operators Lecture 9: Operators continued

Official Form 106A/B Schedule A/B: Property page1 Official Form 106A/B Schedule A/B: Property 12/15 In each category, separately list and describe items. List an asset only once. If an asset fits in more than one c

Carbon Steel DOT 106A forge-welded multi-unit tank car tanks or "ton tanks" for chlorine or other aggressive gases, such as anhydrous ammonia and sulfur dioxide. CBC DOT 106A containers have the exclusive safety-engineered feature of "inverted heads". If a container is accidentally over-pressurized, the heads will reverse, providing an .

Lecture 1: Introduction and Orientation. Lecture 2: Overview of Electronic Materials . Lecture 3: Free electron Fermi gas . Lecture 4: Energy bands . Lecture 5: Carrier Concentration in Semiconductors . Lecture 6: Shallow dopants and Deep -level traps . Lecture 7: Silicon Materials . Lecture 8: Oxidation. Lecture

TOEFL Listening Lecture 35 184 TOEFL Listening Lecture 36 189 TOEFL Listening Lecture 37 194 TOEFL Listening Lecture 38 199 TOEFL Listening Lecture 39 204 TOEFL Listening Lecture 40 209 TOEFL Listening Lecture 41 214 TOEFL Listening Lecture 42 219 TOEFL Listening Lecture 43 225 COPYRIGHT 2016

Partial Di erential Equations MSO-203-B T. Muthukumar tmk@iitk.ac.in November 14, 2019 T. Muthukumar tmk@iitk.ac.in Partial Di erential EquationsMSO-203-B November 14, 2019 1/193 1 First Week Lecture One Lecture Two Lecture Three Lecture Four 2 Second Week Lecture Five Lecture Six 3 Third Week Lecture Seven Lecture Eight 4 Fourth Week Lecture .

moving to straight grades right across the school which will be made up of 3 x Foundation classes, 4 x Gr 1 classes, 3 x Gr 2 classes, 3 x Gr 3 classes, 3 x Gr 4 classes, 4 x Gr 5 classes and 3 x Gr 6 classes. Our Teaching Teams for 2019 will be Foundation Team –