Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring 2011 1 CISC6795: Object Oriented Programming II.

Similar presentations


Presentation on theme: "Spring 2011 1 CISC6795: Object Oriented Programming II."— Presentation transcript:

1 Spring 2011 1 CISC6795: Object Oriented Programming II

2  2005 Pearson Education, Inc. All rights reserved. Outline An introduction to inheritance by example 2

3 Example: Personnel System for a company 3 Different types of employees CommissionEmployee First name, last name, SSN, commission rate, gross sale amount BasePlusCommissionEmployee First name, last name, SSN, commission rate, gross sale amount Base salary

4 4 Declare private instance variables Invoke methods setGrossSales and setCommissionRate to validate data

5 5

6 6 Calculate earnings

7 7

8 CommissionEmployee Class 8 Extends class Object Keyword extends Every class in Java extends an existing class Except Object Every class inherits Object ’s methods New class implicitly extends Object The Java compiler sets the superclass of a class to Object when the class declaration does not explicitly extend a superclass. If it does not extend another class

9 In Java, all classes form a tree The root of the tree: class Object Methods declared for Object clone equals finalize getClass hashCode notify, notifyAll, wait toString C++, it’s a forest … 9

10 10 Instantiate CommissionEmployee objectUse CommissionEmployee ’s get methods to retrieve the object’s instance variable values

11 11 Implicitly call object’s toString method

12 Design BasePlusCommissionEmployee 12 Much of code is similar to C ommissionEmployee instance variables methods constructors Additions/Modifications private instance variable baseSalary Methods setBaseSalary and getBaseSalary Update methods earnings: to add base to commission earnings toString: to display base salary info too

13 Outline 13 Use method setBaseSalary to validate data

14 Outline 14

15 Outline 15

16 Outline 16 Update method earnings to calculate the earnings of a base-salaried commission employee Update method toString to display base salary

17 Outline 17

18 18

19 Reuse through copy 19 Why is this a bad idea ? Spread errors across multiple source code files Maintenance is hard : changes would need to be made to all the source code files that contain a copy of the code in question. Reuse by inheritance Declare common instance variables and methods in superclass, e.g., CommissionEmployee class Subclass inherits superclass’s common feature Introduce changes by overriding methods, adding new instance variables When changes are required for these common features, software developers need only to make changes in the superclass— subclasses then inherit the changes

20 Superclass vs Subclass: is-a 20 Superclass: typically represents larger set of objects than subclasses Subclass represents more specialized group of objects Object of subclass “is an” object of its superclass e.g., a GraduateStudent object is a Student object A BaseSalaryPlusCommissionEmployee object is also a CommissionEmployee object …

21 Subclass is more than super class 21 Absorb superclass’s data and behaviors, is-a relationship Subclass represents more specialized group of objects, i.e., a subclass object is more that just a superclass object Subclass extends superclass: Customizes behaviors inherited from superclass, i.e., overriding methods New capabilities, features: new methods and instance variables

22 Class hierarchy 22 Indirect superclass: inherited two or more levels up hierarchy E.g., HybridCar is a Car, which in turs is a Vehicle Each class extend one single class, i.e., single inheritance C++ support multiple inheritance Java use interface

23 Personnel System: using inheritance 23 Class BasePlusCommissionEmployee2 Extends class CommissionEmployee, Inherits public and protected members Constructor not inherited Enhance with new instance variable baseSalary Enhance with new methods: setBaseSalary, getBaseSalary Customize by overriding two methods: earnings(): so that baseSalary is added into commission income toString(): to display base salary info.

24 24 Invoke the superclass constructor using the superclass constructor call syntax

25 25

26 Outline 26

27 Private member access 27 Private variables and methods are a class’s implementation details Not accessible to the class’s clients: including subclass Solution: use public setter and getter methods provided in superclass (which is inherited by the subclass) Alternatively: use intermediate access modifier, protected private: public: protected:

28 Protected member access 28 protected members of a class are accessible by the class itself, i.e., all member method of the class Subclasses Other classes in the same package No other clients can access them Superclass’s protected members are inherited by all subclases Next code example: use protected member in superclass CommissionEmployee

29 Outline 29 Declare protected instance variables

30 Outline 30

31 Outline 31

32 32

33 33 Must call superclass’s constructor

34 34 Directly access superclass’s protected instance variables

35 35

36 Outline 36

37 Pros and Cons of using protected access 37 Pros subclasses can modify values directly Slight increase in performance Avoid set/get method call overhead Cons No validity checking: subclass might assign illegal value Implementation dependent subclass methods more likely dependent on superclass implementation superclass implementation changes may result in subclass modifications, leading to fragile (brittle) software

38 Software Engineering Observation 38 Declaring superclass instance variables private (as opposed to protected ) enables the superclass implementation of these instance variables to change without affecting subclass implementations. This will ensure that objects of the class maintain consistent states. Best practice in inheritance Superclass: declare instance variables as private, provide public get and set methods Subclass: use get/set method to access values of instance variables

39 Outline 39 Declare private instance variables

40 40

41 41

42 42 Use get methods to obtain the values of instance variables

43 Outline 43 Inherits from CommissionEmployee3

44 Outline 44 Invoke an overridden superclass method from a subclass To refer to superclass’s method: prefix method name with keyword super and a dot (. ) separator What happens if the prefix (super.) is missing ? subclass method calls itself => infinite recursion.

45 Outline 45

46 46

47 Access Modifier for Overriding Methods 47 In above example: All methods are public in superclass These methods must be public in direct or indirect subclass when they are overridden Overriding method in subclass cannot has weaker access modifier than in superclass (same or stronger) Public method of superclass cannot become a protected or private method in subclass Protected method of superclass cannot become a private method in subclass Doing so would break “is-a” relationship, i.e., a subclass object cannot respond to method calls as a superclass object would

48 Constructors in inheritance hierarchy 48

49 Default and No-Argument Constructors 49 Every class must have at least one constructor If no constructors are declared, compiler will create a default no-argument constructor that initializes instance variables to their initial values specified in their declaration or to their default values Default values are zero for primitive numeric types, false for boolean values and null for references If class defines some constructors with argument, compiler does not create default constructor

50 Overloaded Constructors 50 Overloaded constructors: provide multiple constructor definitions with different signatures The this reference can be used to invoke another constructor Allowed only as first statement in a constructor’s body Reuse code whenever possible !

51 Constructors in Subclasses 51 When a subclass constructor is called to instantiate subclass object, a chain of constructor calls happens subclass constructor invokes superclass constructor, implicitly or explicitly To call superclass’s constructor explicitly, call super () in the first statement in the constructor (similar to this () call) If superclass’s constructor is not called explicitly, the superclass’s no- argument constructor is called implicitly superclass constructor in turn calls its superclass’s constructor, implicitly or explicitly … … last constructor called is Object ’s constructor original subclass constructor’s body finishes executing last

52 Outline 52 Constructor outputs message to demonstrate method call order.

53 53 Constructor outputs message to demonstrate method call order. What happens if the super() call is omitted ?

54 Outline 54 Instantiate two BasePlusCommissionEmployee5 objects to demonstrate order of subclass and superclass constructor method calls. Instantiate CommissionEmployee4 object

55 55 Subclass BasePlusCommissionEmployee5 constructor body executes after superclass CommissionEmployee4 ’s constructor finishes execution.

56 Software Engineering Observation 56 Despite the fact that inheriting from a class does not require access to the class’s source code, developers often insist on seeing the source code to understand how the class is implemented. Developers in industry want to ensure that they are extending a solid class—for example, a class that performs well and is implemented securely.

57 Software Engineering Observation 57 At design stage in an object-oriented system, designer often finds that certain classes are closely related. “factor out” common instance variables and methods and place them in a superclass. Use inheritance to develop subclasses, specializing them with capabilities beyond those inherited from superclass. Declaring a subclass does not affect its superclass’s source code. Inheritance preserves integrity of the superclass.

58 Garbage collection and finalize method Life time of an object 58

59 Garbage Collection 59 When is an object born? When we call new to create a new instance of a class Where does an object live? Heap: When does an object cease to exist? When there is no more reference to the object JVM marks an object for garbage collection when there are no more references to that object JVM’s garbage collector will lazily retrieve those objects memory so it can be used for other objects When available memory resource reaches certain low level …

60 Method finalize 60 The superclass of all classes in Java, Object has declared finalize method finalize is called by garbage collector when it performs termination housekeeping A class that uses system resources, such as files on disk, should provide a method to eventually release the resources. Do not perform these operations in finalize method (as Garbage Collector only garbage collector objects when it decides to)… Many Java API classes provide close or dispose methods for this purpose. e.g., class Scanner has a close method.

61 An example Demonstrates finalize, static instance variable, garbage collector 61

62 static Class Members 62 static fields, also known as class variables Represents class-wide information Must be initialized in their declarations, or else compiler will initialize it with a default value ( 0 for int s) Used when: all objects of the class should share same copy of this instance variable this instance variable should be accessible even when no objects exists accessed with class name or an object name and a dot (. ) Always use class name to emphasize that it’s a static field.

63 static class methods 63 static method, also called class method Accessed with class name or an object name and a dot (. ) Invoke static method by class name to emphasize it is a static method. static methods Cannot access non- static class members Cannot use this reference

64 Outline 64 Declare a static field Increment static field

65 Outline 65 Declare method finalize Declare static method getCount to get static field count

66 Outline 66

67 Outline 67 Remove references to objects, JVM will mark them for garbage collection Call static method gc of class System to indicate that garbage collection should be attempted

68 Outline 68

69 System.gc() 69 A static method Indicates that the garbage collector should make a best-effort attempt to reclaim objects eligible for garbage collection It is possible that no objects or only a subset of eligible objects will be collected

70 Misc. Remarks Static import, final instance variables (constants) 70

71 static Import declaration 71 Enables programmers to refer to imported static members as if they were declared in the class that uses them A compilation error occurs if import static methods that have the same signature import static fields that have the same name from two or more classes. Import a specific static member: import static package.Class.staticMember; Import all static members of a class: import static package.Class.*;

72 Outline 72 static import on demand Use Math ’s static methods and instance variable without preceding them with Math.

73 final Instance Variables 73 final instance variables Keyword final: specifies that a variable is not modifiable (is a constant) after it is initialized Must be initialized at their declaration, or initialized in all constructors Principle of least privilege Code should have only the privilege ad access it needs to accomplish its task, but no more Declaring an instance variable as final helps enforce the principle of least privilege. If an instance variable should not be modified, declare it to be final to prevent modification.

74 Outline 74 Declare final instance variable Initialize final instance variable inside a constructor

75 Outline 75

76 Software Engineering Observation 76 A final field should also be declared static if it is initialized in its declaration. Once a final field is initialized in its declaration, its value can never change. Therefore, it is not necessary to have a separate copy of the field for every object of the class. Making the field static enables all objects of the class to share the final field.

77 Packages 77

78 Time Class Case Study: Creating Packages 78 To declare a reusable class, make it a public class Add a package declaration to the source-code file must be the very first executable statement in the file package name should consist of your Internet domain name in reverse order followed by other names for package E.g.: com.deitel.jhtp6.ch08 package name is part of fully qualified class name Prevents name conflict (also called name collision): help to distinguish multiple classes with same name belonging to different packages

79 Outline 79 package declaration Time1 is a public class so it can be used by importers of this package

80 Creating Packages (Cont.) 80 Compile the class so that it is placed in the appropriate package directory structure Example: our package should be in the directory com deitel jhtp6 ch08 javac command-line option –d javac creates appropriate directories based on the class’s package declaration A period (. ) after –d represents the current directory

81 Creating Packages (Cont.) 81 Import the reusable class into a program Single-type-import declaration Imports a single class Example: import java.util.Random; Type-import-on-demand declaration Imports all classes in a package Example: import java.util.*;

82 Common Programming Error 82 Using the import declaration import java. *; causes a compilation error. You must specify the exact name of the package from which you want to import classes.

83 Outline 83 Single-type import declaration Refer to the Time1 class by its simple name

84 Outline 84

85 Creating Packages : class loader 85 Locates classes that the compiler needs First searches standard Java classes bundled with the JDK Then searches for optional packages These are enabled by Java’s extension mechanism Finally searches the classpath List of directories or archive files separated by directory separators These files normally end with.jar or.zip Standard classes are in the archive file rt.jar

86 Creating Packages: Class Loader 86 To use a classpath other than the current directory -classpath option for the javac compiler Set the CLASSPATH environment variable Specifying an explicit classpath eliminates current directory from the classpath. This prevents classes in the current directory (including packages in the current directory) from loading properly. If classes must be loaded from the current directory, include a dot (. ) in the classpath to specify the current directory. The JVM must locate classes just as the compiler does The java command can use other classpathes by using the same techniques that the javac command uses

87 Software Engineering Observation 87 In general, it is a better practice to use the - classpath option of the compiler, rather than the CLASSPATH environment variable, to specify the classpath for a program. This enables each application to have its own classpath.

88 Package Access 88 Package access Methods and variables declared without any access modifier are given package access This has no effect if the program consists of one class This does have an effect if the program contains multiple classes from the same package Package-access members can be directly accessed through the appropriate references to objects in other classes belonging to the same package

89 Outline 89 Package-access instance variables

90 Outline 90 Can directly access package-access members

91 Summary 91

92 Acknowledgement Part of the slides are updated from Java How To Program, 1992-2010 by Pearson Education, Inc. All Rights Reserved. 92


Download ppt "Spring 2011 1 CISC6795: Object Oriented Programming II."

Similar presentations


Ads by Google