Bài giảng An Introduction to Computer Science Using Java - Chapter 7 Classes and Methods III: Static Methods and Variables

Tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 7 Classes and Methods III: Static Methods and Variables: Chapter 7 Classes and Methods III: Static Methods and VariablesLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:describe user-defined classesinstance variablesconstructors instance methodspresent several examples of classesdiscuss the concepts of mutability and visibilitydescribe method overloadingObject-Oriented ProgrammingOOP supports the view that programs are composed of interacting objectsObjects are composed ofvalues known as attributes or instance variablesoperations (actions) that can be performed on these values know as instance methodsMessages requesting an action or value are sent to objectsObjects respond to messages that are in their protocols or interfacesObjectsEncapsulate data values within a single entityTheir behavior is often general enough to allow reuse in a variety of situationsOften form a basis from which other objects can be derived using a mechani...

ppt39 trang | Chia sẻ: honghanh66 | Lượt xem: 848 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 7 Classes and Methods III: Static Methods and Variables, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 7 Classes and Methods III: Static Methods and VariablesLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:describe user-defined classesinstance variablesconstructors instance methodspresent several examples of classesdiscuss the concepts of mutability and visibilitydescribe method overloadingObject-Oriented ProgrammingOOP supports the view that programs are composed of interacting objectsObjects are composed ofvalues known as attributes or instance variablesoperations (actions) that can be performed on these values know as instance methodsMessages requesting an action or value are sent to objectsObjects respond to messages that are in their protocols or interfacesObjectsEncapsulate data values within a single entityTheir behavior is often general enough to allow reuse in a variety of situationsOften form a basis from which other objects can be derived using a mechanism known as inheritanceAre a type container that is stored on the system heapA client is program that uses an objectClient RightsTo declare variables of the class typeTo create instances of the class using constructorsTo send messages to instances of the class by invoking class instance methodsTo know the class public interfaceinstance method namesparameter number and typesreturn typesTo know the instance methods that alter (mutate) the instanceClass RightsTo define the class public interfaceTo hide all the implementation details from the clientTo protect internal data from client accessTo change implementation details at any time, provided the public interface remains intact To change the public interface with client concurrenceRevised Class Definitionpublic class name { declarations of instance variables constructor definitions method definitions}Every class needs one or more constructor definitionsRevised Class DefinitionInstance variableslocal data contained in class Method definitionsdescribe the class interface and how it responds to each client messageConstructors definitionsdescribe how to initialize instance variables in a new object ConstructorsLook like regular instance methodsNever have a return typeAlways have the same name as the class nameMay have parametersDefault constructors have no parametersConstructors can be overloaded (more than one definition in the same class)Constructorspublic class Clock { int hour, minute; // constructor public Clock( ) { hour = 12; minute = 0; } // other methods follow }Using Constructors// c1 set to 12:00Clock c1 = new Clock(); // c1 set to 8:30 c1.setHour(8);c1.setMinute(30);// c2 set to 12:00 c1 still 8:30Clock c2 = new Clock();Overloading ConstructorsClasses can have more than one constructorAll constructors have the same name (the class name)Each constructor differs from the others in either the number or types of its argumentsnew is used when using a constructor to create a new objectOverloading ConstructorsWe could add the following to Clock public Clock(int h, int m) { hour = h; minute = m; }A client program could contain Clock c1 = new Clock(8, 20);Which is the same as writing Clock c1 = new Clock( ); c1.setHour(8); c1.setMinute(20);Overloaded Clock Constructorspublic class Clock { int hour, minute; public Clock () { hour = 12; minute = 0; } public Clock (int h, int m){ hour = h; minute = m; } }Using ConstructorsClock c1 = new Clock( ); // c1 set to 12:00Clock c2 = new Clock(8, 20); // c2 set to 8:20Clock c3 = new Clock(); // c3 set to 8:20c3.setHour(8);C3/setMinute(20);Overloading MethodsMethods can also be overloadedThis allows different versions of the method in the same classEach method variant must differ from the others by the number or types of its parametersOverloading allows methods with the same name to have different return typesMethods Calling Other MethodsMethods are allowed to call other methods in the same class without specifying an explicit receiverThis allows overloaded methods to call one another without repeating redundant codeExample:public void display (DrawingBox d, int r) { display(d, d.getDrawableWidth()/2, d.getDrawableHeight()/2, r);}Dot NotationWe can also use dot notation to view instance variables of the same class that are different from the receiverExample:public boolean priorTo (Clock c) { return (hour < c.hour || hour == c.hour && minute < c.minute);} this – Avoiding Variable Name Collisions“this” can be used to distinguish between references to instance variables and local identifiers or argumentspublic void set (int hour, int minute) { int totalMinutes = (hour * 60 + minutes); this.minute = totalMinutes % 60;}this.minute refers to the instance variable minute not the method argumentthis – Passing the Receiver as an Argument “this” can be used to send a message to the current receiver of the message without explicitly naming the receiverpublic boolean after (Clock c) { return c.priorTo(this);}this is used as if it were a variable referring to the receiver of the messagethis – Chaining Constructors “this” can be used to simplify constructor code by allowing one constructor to call anotherWe can rewrite the clock constructors as:public Clock ( ) { this(12,0);}public Clock (int hour, int minute) { set(hour, minute);}Visibility Qualifierspublic int x; // client creating instance o of this // class can access x by writing o.xprivate int y; // no can access y directly, access // provided though class methodsTo enforce complete information hiding all instance variables should be declared using privateThe default visibility of instance variables lies between private and public (explained later in the text)Visibility Qualifiers and MethodsBy default class methods are also accessible to some classes but not othersVisibility qualifiers should also be used in method declarationsExamples:public void f( ) { // Any client using object o // can send it a message // by writing o.f( )private void g( ) { // No client can send g to // the object except another // method from this classVisibility and UML DiagramsIn UML diagrams private variables and methods are indicated using a leading minus sign as a prefixpublic variables and methods are indicates using a leading plus sign as a prefixa blank prefix means that the variables and methods are not annotated and will have their default visibilityMutationAn object can be changed by assigning a new value to one or more of its instance variablesExample:d = new DrawingBox();c = new Clock();c.set(10, 20);c.display(d, 50, 50, 50);c.set(5, 40);MutabilityTransforming an object from one state to anotherOnly objects can be mutated, primitive values are not (e.g. x+4 does not change x)Objects are only mutable if its interface includes mutating methodsNonmutationCreating a new object similar to original, but including the desired changeNote the return type is Clock, not voidExample:public Clock set_nonmut (int hour, int Minute) { return new Clock(hour, minute);}What would happen?Consider the effects on the heap if the following sequence of statements was executedClock c1 = new Clock();Clock c2 = c1;c1.set(4, 30);c2.set(5, 40); Heap After Assigning c1 to c2Class AssociationUsed to achieve certain desired behaviorAssociation (or acquaintance)classes and objects are linked in a manner that allows the object to remain visible to clientsclasses can be linked when a client passes an object as a message argument to another objectObject Containing Reference to Another ObjectUML Class Diagram for Clock-DrawingBox AssociationUML Class Diagram for Clock-DrawingBox AssociationClass ContainmentComposition (or aggregation)an object of one class is constructed from objects of other classes so that only the composite object is visible to clientsthe component objects are internal to the containing object Aggregation is a weaker form of containment and will not be used in this textUML Class Diagram for Clock-DrawingBox CompositionRepresentation IndependenceIn OOP the representation of data is encapsulated, this means that the data representation may be changed without affecting the previous class behaviorClients should not be able to detect that a change has occurredSometimes this is know as implementation independence mainEvery Java program needs a class containing a static method called mainStatic methods (or class methods) are special methods that do not require receiversStatic methods cannot refer to class instance variables, but can be invoked when no class instances existStatic methods will be discussed in more detail in Chapter 10

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

  • pptchapter7_5867.ppt
Tài liệu liên quan