Transcript
  • Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

    CS106A,Lecture22MoreClasses

    suggestedreading:JavaCh.6

  • 2

    Learning Goals• Knowhowtodefineourownvariabletypes• Knowhowtodefinevariabletypesthatinheritfromothertypes• Beabletowriteprogramsconsistingofmultipleclasses

  • 3

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 4

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 5

    What Is A Class?

    Aclassdefinesanewvariabletype.

  • 6

    Classes Are Like BlueprintsiPodblueprint(class)

    state:currentsongvolumebatterylifebehavior:poweron/offchangestation/songchangevolumechooserandomsong

    iPod(variable)#1state:song="1,000,000Miles"volume=17batterylife=2.5hrsbehavior:poweron/offchangestation/songchangevolumechooserandomsong

    iPod(variable)#2state:song="LettingYou"volume=9batterylife=3.41hrsbehavior:poweron/offchangestation/songchangevolumechooserandomsong

    iPod(variable)#3state:song="Discipline"volume=24batterylife=1.8hrsbehavior:poweron/offchangestation/songchangevolumechooserandomsong

    constructs

  • 7

    What if…Whatifwecouldwriteaprogramlikethis:

    BankAccount nickAccount = new BankAccount();nickAccount.setName(“Nick”);nickAccount.deposit(50);

    BankAccount rishiAccount = new BankAccount();rishiAccount.setName(“Rishi”);rishiAccount.deposit(50);boolean success = rishiAccount.withdraw(10);if (success) {

    println(“Rishi withdrew $10.”);}

  • 8

    Creating A New Class1. Whatinformationisinsidethisnewvariabletype? Theseareitsprivateinstancevariables.

  • 9

    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.

  • 10

    Creating A New Class1. Whatinformationisinsidethisnewvariabletype? Theseareitsinstancevariables.

    2. Whatcanthisnewvariabletypedo?Theseareitspublicmethods.

  • 11

    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;

    }}

  • 12

    Defining Methods In ClassesMethodsdefinedinclassescanbecalledonaninstanceofthatclass.

    Whenoneofthesemethodsexecutes,itcanreferencethatobject’scopy ofinstancevariables.

    ba1.deposit(0.20);ba2.deposit(1000.00);

    Thismeanscallingoneofthesemethodsondifferentobjectshasdifferenteffects.

    name = "Marty"balance = 1.45deposit(amount) {

    balance += amount;}

    name = "Mehran"balance = 901000.00deposit(amount) {

    balance += amount;}

    ba1

    ba2

  • 13

    Getters and SettersInstancevariablesinaclassshouldalwaysbeprivate.Thisissoonlytheobjectitselfcanmodifythem,andno-oneelse.

    Toallowtheclienttoreferencethem,wedefinepublicmethodsintheclassthatset aninstancevariable’svalueandget (return)aninstancevariable’svalue.Thesearecommonlyknownasgetters andsetters.

    account.setName(“Nick”);String accountName = account.getName();

    Gettersandsetterspreventinstancevariablesfrombeingtamperedwith.

  • 14

    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;

    }}

  • 15

    Creating A New Class1. Whatinformationisinsidethisnewvariabletype? Theseareitsinstancevariables.

    2. Whatcanthisnewvariabletypedo?Theseareitspublicmethods.

    3. Howdoyoucreateavariableofthistype?Thisistheconstructor.

  • 16

    ConstructorsBankAccount ba1 = new BankAccount();

    BankAccount ba2 = new BankAccount(“Nick”, 50);

    The constructor is executed when a new object is created.

  • 17

    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;

    }}

  • 18

    Using ConstructorsBankAccount ba1 =

    new BankAccount("Marty", 1.25);

    BankAccount ba2 =new BankAccount("Mehran", 900000.00);

    • Whenyoucallaconstructor(withnew):– Javacreatesanewobjectofthatclass.– Theconstructorruns,onthatnewobject.– Thenewlycreatedobjectisreturnedtoyourprogram.

    name = "Marty"balance = 1.25BankAccount(nm, bal) {

    name = nm;balance = bal;

    }

    name = "Mehran"balance = 900000.00BankAccount(nm, bal) {

    name = nm;balance = bal;

    }

    ba1

    ba2

  • 19

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 20

    Printing Variables• Bydefault,Javadoesn'tknowhowtoprintobjects.

    // ba1 is BankAccount@9e8c34BankAccount ba1 = new BankAccount("Marty", 1.25);println("ba1 is " + ba1);

    // better, but cumbersome to write// ba1 is Marty with $1.25println("ba1 is " + ba1.getName() + " with $"

    + ba1.getBalance());

    // desired behaviorprintln("ba1 is " + ba1); // ba1 is Marty with $1.25

  • 21

    The toString MethodAspecialmethodinaclassthattellsJavahowtoconvertanobjectintoastring.

    BankAccount ba1 = new BankAccount("Marty", 1.25);println("ba1 is " + ba1);

    // the above code is really calling the following:println("ba1 is " + ba1.toString());

    • EveryclasshasatoString,evenifitisn'tinyourcode.– Default:class'sname@ object'smemoryaddress(base16)

    BankAccount@9e8c34

  • 22

    The toString Methodpublic String toString() {

    code that returns a Stringrepresenting this object;

    }

    – Methodname,return,andparametersmustmatchexactly.

    – Example:// Returns a String representing this account.public String toString() {

    return name + " has $" + balance;}

  • 23

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 24

    The “this” Keywordthis:Referstotheobjectonwhichamethodiscurrentlybeingcalled

    BankAccount ba1 = new BankAccount();ba1.deposit(5);

    // in BankAccount.javapublic void deposit(double amount) {

    // for code above, “this” -> ba1...

    }

  • 25

    Using “this”Sometimeswewanttonameparametersthesameasinstancevariables.

    public class BankAccount {private double balance;private String name;...

    public void setName(String newName) {name = newName;

    }}

    – Here,theparametertosetName isnamednewName tobedistinctfromtheobject'sfieldname .

  • 26

    Using “this”public class BankAccount {

    private double balance;private String name;...

    public void setName(String name) {name = name;

    }}

  • 27

    Using “this”Wecanuse“this”tospecifywhichoneistheinstancevariableandwhichoneisthelocalvariable.

    public class BankAccount {private double balance;private String name;...

    public void setName(String name) {this.name = name;

    }}

  • 28

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 29

    Practice: EmployeeLet’sdefineanewvariabletypecalledEmployeethatrepresentsasingleEmployee.

    WhatinformationwouldanEmployeestore?

    WhatcouldanEmployeedo?

    HowwouldyoucreateanewEmployeevariable?

  • 30

    Plan for today•Recap:Classes•toString•this•Example: Employee•Inheritance

  • 31

    Inheritance

    Inheritanceletsusrelateourvariable

    typestooneanother.

  • 32

    Inheritance

    Employee

    Programmer

    KarelProgrammer

    Variabletypescanseemto“inherit”fromeachother.Wedon’twanttohavetoduplicatecodeforeachone!

  • 33

    Example: GObjects• TheStanfordlibraryusesaninheritancehierarchyofgraphicalobjectsbasedonacommonsuperclassnamedGObject.

  • 34

    Example: GObjects• GObject definesthestateandbehaviorcommontoallshapes:

    contains(x, y)getColor(), setColor(color)getHeight(), getWidth(), getLocation(), setLocation(x, y)getX(), getY(), setX(x), setY(y), move(dx, dy)setVisible(visible), sendForward(), sendBackward()toString()

    • Thesubclassesaddstateandbehavioruniquetothem:GLabel GLine GPolygon

    get/setFont get/setStartPoint addEdgeget/setLabel get/setEndPoint addVertex

    get/setFillColor... ... ..

  • 35

    Using Inheritancepublic class Name extends Superclass {

    – Example:

    public class Programmer extends Employee {...

    }

    • ByextendingEmployee,thistellsJavathatProgrammer candoeverythinganEmployeecando,plusmore.

    • ProgrammerautomaticallyinheritsallofthecodefromEmployee!• ThesuperclassisEmployee,thesubclass isProgrammer.

  • 36

    Example: Programmerpublic class Programmer extends Employee {

    private int timeCoding;...public void code() {

    timeCoding += 10;}

    }

    ...

    Programmer rishi = new Programmer(“Rishi”);rishi.code(); // from Programmerrishi.promote(); // from Employee!

  • 37

    Example: KarelProgrammerpublic class KarelProgrammer extends Programmer {

    private int numBeepersPicked;...public void pickBeepers() {

    numBeepersPicked += 2;}

    }

    ...KarelProgrammer nick = new KarelProgrammer(“Nick”);nick.pickBeepers(); // from KarelProgrammernick.code(); // from Programmer!nick.promote(); // From Employee!

  • 38

    GCanvas• AGCanvas isthecanvasareathatdisplaysallgraphicalobjectsinaGraphicsProgram.

    • WhenyoucreateaGraphicsProgram,itautomaticallycreatesaGCanvas foritself,putsitonthescreen,andusesittoaddallgraphicalshapes.

    • GCanvas istheonethatcontainsmethodslike:– getElementAt– add– remove– getWidth– getHeight– …

  • 39

    GCanvaspublic class Graphics extends GraphicsProgram {

    public void run() {// A GCanvas has been created for us!GRect rect = new GRect(50, 50);add(rect); // adds to the GCanvas!

    ...// Checks our GCanvas for elements!GObject obj = getElementAt(25, 25);

    }}

  • 40

    Extending GCanvaspublic class Graphics extends Program {

    public void run() {// We have to make our own GCanvas nowMyCanvas canvas = new MyCanvas();add(canvas);

    // Can’t do this anymore, because we are // not using GraphicsProgram’s provided // canvasGObject obj = getElementAt(…);

    }}

  • 41

    Extending GCanvaspublic class MyCanvas extends GCanvas {

    public void addCenteredSquare(int size) {GRect rect = new GRect(size, size);int x = getWidth() / 2.0 –

    rect.getWidth() / 2.0;int y = getHeight() / 2.0 –

    rect.getHeight() / 2.0;add(rect, x, y);

    }}

  • 42

    Extending GCanvaspublic class Graphics extends Program {

    public void run() {// We have to make our own GCanvas nowMyCanvas canvas = new MyCanvas();add(canvas);

    canvas.addCenteredSquare(20);}

    }

  • 43

    Extending GCanvas•Sometimes,wewanttobeabletohaveallofourgraphics-relatedcodeinaseparatefile.

    •Todothis,insteadofusingtheprovidedGraphicsProgram canvas,wedefineourownsubclassofGCanvas, haveourprogramextendProgram,andaddourowncanvasourselves.

    •Then,allgraphics-relatedcodecangoinourGCanvas subclass.

  • 44

    Recap•Classesletusdefineourownvariabletypes,withtheirowninstancevariables,methodsandconstructors.

    •Wecanrelate ourvariabletypestooneanotherbyusinginheritance.Oneclasscanextend anothertoinherititsbehavior.

    •WecanextendGCanvas inagraphicalprogramtodecomposeallofourgraphics-relatedcodeinoneplace.

    Nexttime: InteractorsandGUIs


Top Related