Kiến trúc máy tính và hợp ngữ - Objects and classes

A method can return a value to the caller The keyword void in the method’s header indicates that the method does not return any value

ppt35 trang | Chia sẻ: huyhoang44 | Lượt xem: 802 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kiến trúc máy tính và hợp ngữ - Objects and classes, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Objects and ClassesCopyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.Java MethodsObject-Oriented Programmingand Data StructuresMaria Litvin ● Gary Litvin2nd AP edition  with GridWorld1Objectives:See an example of a GridWorld program, written in OOP style, and discuss the types of objects used in itLearn about the general structure of a class, its fields, constructors, and methodsGet a feel for how objects are created and how to call their methodsLearn a little about inheritance in OOP2OOPAn OO program models the application as a world of interacting objects.An object can create other objects.An object can call another object’s (and its own) methods (that is, “send messages”).An object has data fields, which hold values that can change while the program is running.3ObjectsCan model real-world objectsCan represent GUI (Graphical User Interface) componentsCan represent software entities (events, files, images, etc.)Can represent abstract concepts (for example, rules of a game, a location on a grid, etc.)4Objects in the Bug Runner programGridControl panelBugs, flowers, and rocksMessage displayGridWorld windowLocations (in the grid)Buttons, sliderMenu bar, menusScroll barColors5Classes and ObjectsA class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions.An object is called an instance of a class. A program can create and use more than one object (instance) of the same class.6 Class ObjectA blueprint for objects of a particular typeDefines the structure (number, types) of the attributesDefines available behaviors of its objectsAttributesBehaviors7Class: Car Object: a carAttributes: String model Color color int numPassengers double amountOfGasBehaviors: Add/remove a passenger Get the tank filled Report when out of gasAttributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5Behaviors: 8 Class vs. ObjectA piece of the program’s source codeWritten by a programmer An entity in a running programCreated when the program is running (by the main method or a constructor or another method) 9 Class vs. ObjectSpecifies the structure (the number and types) of its objects’ attributes — the same for all of its objectsSpecifies the possible behaviors of its objects Holds specific values of attributes; these values can change while the program is runningBehaves appropriately when called upon 10CRC CardA preliminary description of a class at the initial stage of program designCollaboratorsClassResponsibilities11Classes and Source FilesEach class is stored in a separate fileThe name of the file must be the same as the name of the class, with the extension .javapublic class Car{ ...}Car.javaBy convention, the name of a class (and its source file) always starts with a capital letter. (In Java, all names are case-sensitive.)12LibrariesJava programs are usually not written from scratch.There are hundreds of library classes for all occasions.Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package13importFull library class names include the package name. For example: java.awt.Color javax.swing.JButtonimport statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton; ... JButton go = new JButton("Go");Fully-qualified name14import (cont’d)You can import names for all the classes in a package by using a wildcard .*: import java.awt.*; import java.awt.event.*; import javax.swing.*;java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes.Imports all classes from awt, awt.event, and swing packages15import (cont’d)GridWorld has its own library (gridworld.jar)You need to tell the compiler where to find GridWorld classes: import info.gridworld.grid.Grid; import info.gridworld.grid.Location; ... import info.gridworld.actor.Bug; import info.gridworld.actor.Flower; ...16public class SomeClassFieldsConstructorsMethods}Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objectsProcedures for constructing a new object of this class and initializing its fieldsActions that an object of this class can take (behaviors){Class headerSomeClass.javaimport ...import statements17public class Actor{ private Grid grid; private Location location; private int direction; private Color color; public Actor() { color = Color.BLUE; direction = Location.NORTH; grid = null; location = null; } ... public void moveTo(Location newLocation) { ... } ...} FieldsConstructor(s)Methods18FieldsA.k.a. instance variablesConstitute “private memory” of an objectEach field has a data type (int, double, String, Color, Location, etc.)Each field has a name given by the programmer19private [static] [final] datatype name;Fields (cont’d)Usually privateMay be present: means the field is a constantint, double, etc., or an object: String, Location, ColorYou name it!May be present: means the field is shared by all objects in the classprivate Location location;20ConstructorsShort procedures for creating objects of a classAlways have the same name as the classInitialize the object’s fieldsMay take parametersA class may have several constructors that differ in the number and/or types of their parameters21Constructors (cont’d)public class Location{ private int row; private int col; ... public Location (int r, int c) { row = r; col = c; } ...} The name of a constructor is always the same as the name of the classA constructor can take parametersInitializes fields22Constructors (cont’d)public class Location{ ... public Location (int r, int c) { ... } ...} // BugRunner.java ... Location loc = new Location(3, 5); ...An object is created with the new operatorThe number, order, and types of parameters must matchConstructor23Constructors (cont’d)JButton go = new JButton("Go");24MethodsCall them for a particular object:ActorWorld world = new ActorWorld();Bug bob = new Bug();world.add (new Location(3, 5), bob);bob.move( );bob.turn( );25Methods (cont’d)The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters:g.drawString ("Welcome", 120, 50); public void drawString ( String msg, int x, int y ) { ... }26Methods (cont’d)A method can return a value to the callerThe keyword void in the method’s header indicates that the method does not return any value public void drawString ( ... ) { ... } 27Encapsulation and Information HidingA class interacts with other classes only through constructors and public methodsOther classes do not need to know the mechanics (implementation details) of a class to use it effectivelyEncapsulation facilitates team work and program maintenance (making changes to the code)28Methods (cont’d)Constructors and methods can call other public and private methods of the same class.Constructors and methods can call only public methods of another class.Class Xprivate field private methodClass Y public method public method29InheritanceIn OOP a programmer can create a new class by extending an existing classSuperclass(Base class)Subclass(Derived class)subclass extends superclass30Inheritance (cont’d)BugUTurnBugUTurnBug extends BugActorBug extends Actor31A Subclass...inherits fields and methods of its superclasscan add new fields and methodscan redefine (override) a method of the superclassmust provide its own constructors, but calls superclass’s constructorsdoes not have direct access to its superclass’s private fields32public class UTurnBug extends Bug{ public UTurnBug (Color bugColor) { setColor (bugColor); } ... public void turnAround () { turn(); turn(); turn(); turn(); // Or: setDirection (getDirection() + 180); } ...}A new methodConstructor33Review:Name a few objects used in GridWorld’s BugRunner.Name a few library classes used in GridWorld.What are import statements used for?What is a field? A constructor? A method?Which operator is used to construct an object?34Review (cont’d):What is the difference between private and public methods?Why are fields usually private?What is inheritance?Can a subclass add new fields? New methods?35

Các file đính kèm theo tài liệu này:

  • pptch03_7274.ppt