Presentation is loading. Please wait.

Presentation is loading. Please wait.

OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,

Similar presentations


Presentation on theme: "OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,"— Presentation transcript:

1 OOP Review

2 Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism, Dynamic Binding

3 Object Definition: a thing that has identity, state, and behavior Õidentity: a distinguished instance of a class Õstate: collection of values for its variables Õbehavior: capability to execute methods * variables and methods are defined in a class

4 Class Definition: a collection of data (fields/ variables) and methods that operate on that data Õdata/methods define the contents/capabilities of the instances (objects) of the class Õa class can be viewed as a factory for objects Õa class defines a recipe for its objects

5 Instantiation zObject creation zMemory is allocated for the object’s fields as defined in the class zInitialization is specified through a constructor Õa special method invoked when objects are created

6 Encapsulation zA key OO concept: “Information Hiding” zKey points ÕThe user of an object should have access only to those methods (or data) that are essential ÕUnnecessary implementation details should be hidden from the user ÕIn Java, use classes and access modifiers (public, private, protected)

7 Inheritance zInheritance: ÕProgramming language feature that allows for the implicit definition of variables/methods for a class through an existing class zSubclass relationship ÕB is a subclass of A ÕB inherits all definitions (variables/methods) in A

8 Abstraction zOOP is about abstraction zEncapsulation and Inheritance are examples of abstraction ÕWhat does the verb “abstract” mean?

9 Reuse zInheritance encourages software reuse zExisting code need not be rewritten zSuccessful reuse occurs only through careful planning and design Õwhen defining classes, anticipate future modifications and extensions

10 Polymorphism z“Many forms” Õallow several definitions under a single method name zExample: Õ“move” means something for a person object but means something else for a car object zDynamic binding: Õcapability of an implementation to distinguish between the different forms during run-time

11 Visual and Event-driven Programming zFits very well with the OO Paradigm zVisual Programming and GUIs Õwindows, icons, buttons, etc. are objects created from ready-made classes zEvent-driven Programming Õexecution associated with user interaction with visual objects that causes the invocation of other objects’ methods

12 OOP and Object Interaction zObjects pass messages to each other zAn object responds to a message by executing an associated method defined in its class zCauses a “chain reaction” zThe user could be viewed as an object zDepicted in an Interaction Diagram

13 Java Review

14 What is Java? Java is a general purpose programming language that is: Õobject-oriented Õinterpreted, architecture-neutral, portable Õdistributed (network-aware), secure Õsimple, robust Õmulti-threaded Õhigh-performance (?)

15 Two Types of Java Programs zApplications Õgeneral-purpose programs Õstandalone Õexecuted through the operating system zApplets Õprograms meant for the WWW Õembedded in a Web page Õnormally executed through a browser

16 Fundamental Language Issues zCompilation and Execution zData Types zVariables zStatements zArrays zOthers

17 Java Program Compilation and Execution zProg.java is compiled to Prog.class Õjavac Prog.java zExecution Õfor applets, the browser loads Prog.class (specified in html file) and UI events can then be processed Õfor applications, a Java interpreter loads Prog.class and causes program execution to begin in the “main()” method of this class

18 The Java Virtual Machine zBrowsers and the Java interpreters have to simulate this “standard” machine z“Compile once, run anywhere” zClass Loader ÕThe JVM facilitates the loading and execution of classes ÕSeveral classes, not just one class, are loaded ÕJava class library

19 Data Types zPrimitive types Õint, double, char, float, long, boolean, byte zData type sizes ÕIn Java, the size of a data type type is strictly specified

20 Sizes and Ranges for some Java Types zint: 4 bytes Õ-2,147,483,648 to 2,147,483,647 zfloat: 4 bytes Õ1.01e-45 to 3.40e+38 zdouble 8 bytes Õ4.94e-324 to 1.80e+308

21 Sizes and Ranges for some Java Types zboolean: true, false Õsize: 1 bit ÕNot compatible with integer types as in C zchar: Unicode character set Õsize: 2 bytes ÕSuperset of ASCII ÕInternationalization ÕStill compatible with integer types

22 Two Kinds of Variables zVariables of a primitive type e.g., int x; char c; zVariables of a reference type (class) e.g., Button b; String s; zConventions ÕPrimitive types are reserved words in Java and are indicated in all-lower-case letters ÕClass names: first letter usually capitalized

23 Variables and Values zPrimitive type variables int x; … x = 5; 5 X X

24 Variables and References zReference type variables Button x; … x = new Button(“copy”); X X “copy” Button Object

25 The new Keyword znew Button(“copy”) creates a Button object and returns a reference (an address) to that object that a Button variable could hold “copy” Button Object 1023: 1023 is some address in memory 1023 X

26 The null Keyword zUse null to indicate (or test) that the variable does not currently refer to an object x = null; if (x == null)... null X

27 Statements zExpression statements ÕOperations, assignment, function calls zControl structures Õif, switch, while, do-while, for, try-catch (for exception handling) zIn a compound statement or block ({…}), variable declarations and statements may intersperse

28 Arrays zDeclaration: double nums[]; zCreation:nums = new double[8]; zUse:nums[3] = 6.6; * Note: starting index is 0 (0 to 7, above)

29 Visualizing an Array 6.6 nums double nums[]; nums = new double[8]; nums[3] = 6.6;

30 Array of Objects TextField object slots TextField object

31 Classes and Objects in Java

32 Variables and Objects Let Circle be a class with: variable r that indicates its radius method area() that computes its area ÕDeclaration:Circle c; ÕInstantiation:c = new Circle(); ÕUsage:c.r = 5.5; System.out.println(c.area());

33 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference() { return 2*3.14*r; } public double area() { return 3.14*r*r; } }

34 Using the Circle class public class TestCircle { public static void main(String args[]) { Circle c; c = new Circle(); c.x = 2.0; c.y = 2.0; c.r = 5.5; System.out.println(c.area()); }

35 The Dot (“.”) Operator zAllows access to variables (primitive and reference types) and methods of reference type variables. zExample: TextField t = new TextField(10); t.setText(“hi”); // accessing the setText method

36 Method Invocation zSyntax for method invocation object.methodName(arguments) zMethod may return a value or simply produce an effect on the object zTo find out what methods are available for a given class Õjavap package.name.NameOfClass Õe.g., javap java.awt.Button, or javap Circle

37 The this keyword zthis refers to the current object zIn the Circle class, the following definitions for area() are equivalent: public double area() { return 3.14 * r * r; } public double area() { return 3.14 * this.r * this.r; } zUsing the keyword clarifies that you are referring to a variable inside an object Õdot operator used consistently

38 Constructors zA constructor is a special type of method Õhas the same name as the class zIt is called when an object is created Õnew Circle(); // “calls” the Circle() method zIf no constructor is defined, a default constructor that does nothing is implemented

39 A constructor for the Circle class public class Circle { public double x,y; // center coordinates public double r; // radius public Circle() { // sets default values for x, y, and r this.x = 0.0; this.y = 0.0; this.r = 1.0; }... }

40 A constructor with parameters public class Circle { … public Circle(double x, double y, double z) { this.x = x; this.y = y; this.r = z; // using this is now a necessity }... }

41 Using the different constructors Circle c, d; c = new Circle(); // radius of circle has been set to 1.0 System.out.println(c.area()); d = new Circle(1.0,1.0,5.0); // radius of circle has been set to 5.0 System.out.println(d.area());

42 Method Overloading zIn Java, it is possible to have several method definitions under the same name Õ but the signatures should be different zSignature: Õthe name of the method Õthe number of parameters Õthe types of the parameters

43 Encapsulation in Java zAccess modifiers zpublic Õa public variable/method is available for use outside the class it is defined in zprivate Õa private variable/method may be used only within the class it is defined in

44 The Circle class Revisited public class Circle { private double x,y; // center coordinates private double r; // radius //... } // when using the Circle class... Circle c; c.r = 1.0; // this statement is not allowed

45 Outside access to private data zNo direct access zDefine (public) set and get methods instead or initialize the data through constructors zWhy? ÕIf you change your mind about the names and even the types of these private data, the code using the class need not be changed

46 Set and Get Methods zVariables/attributes in a class are often not declared public zInstead: Õdefine use a (public) set method to assign a value to a variable Õdefine a get method to retrieve that value zStill consistent with encapsulation

47 Set and Get Methods for Radius public class Circle { //... private double r; // radius // … public void setRadius(double r) { this.r = r; } public double getRadius() { return this.r; } //... }

48 Inheritance

49 Inheritance and the extends Keyword zIn Java, public class B extends A { … } Õmeans B is a subclass of A Õobjects of class B now have access* to variables and methods defined in A

50 The EnhancedCircle class public class EnhancedCircle extends Circle { // as if area(), circumference(), setRadius() and getRadius() // automatically defined; x,y,r are also present (but are private // to the the Circle class) private int color; public void setColor(int c) { this.color = c; } public void draw() { … } public double diameter() { return this.getRadius()*2; } }

51 Using a Subclass EnhancedCircle c; c = new EnhancedCircle(); // Circle() constructor // implicitly invoked c.setColor(5); c.setRadius(6.6); System.out.println(c.area()); System.out.println(c.diameter()); c.draw();

52 Superclass Variables, Subclass Objects zLet B be a subclass of A zIt is legal to have variables of class A to refer to objects of class B zExample Circle c; … c = new EnhancedCircle();

53 Method Overriding zA method (with a given signature) may be overridden in a subclass zSuppose class B extends A Õlet void operate() be a method defined in A Õvoid operate() may be defined in B Õobjects of class A use A’s operate() Õobjects of class B use B’s operate()

54 Dynamic Binding zLet A be a superclass of subclasses B and C zA variable of class A may refer to instances of A, B, and C zJava facilitates the calling of the appropriate method at run time zExample ÕA v; … v.operate();

55 Constructors and Superclasses zSuppose B extends A Õnew B() calls B’s constructor Õhow about A’s constructor ? zRule Õthe constructor of a superclass is always invoked before the statements in the subclass’ constructor are executed

56 super() zUsed to call a superclass’ constructor zImplicitly included when not indicated If B extends A, the following are equivalent:public B() { // body of constructor super(); } // body of constructor }

57 Calling a particular Constructor zUse super with parameters if a particular constructor should be called zExample: public class BlueButton extends Button { public BlueButton(String s) { super(s); // without this, super() is called (label-less) setBackground(Color.blue); } … }

58 More Uses for super zWhen overriding a method, one can merely “extend” the method definition public class Manager extends Employee { public void increase() { super.increase(); // call Employee’s increase // do more stuff }


Download ppt "OOP Review. Key OOP Concepts zObject, Class zInstantiation, Constructors zEncapsulation zInheritance and Subclasses zAbstraction zReuse zPolymorphism,"

Similar presentations


Ads by Google