1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Bài giảng điện tử môn tin học: Object-Oriented Programming ppsx

92 574 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 92
Dung lượng 558,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Introduction, cont Object-Oriented Programming  Introduce protected member access  Relationships  "is a" - inheritance  Object of subclass "is a" object of the superclass  "has a"

Trang 1

Part II: Object-Oriented Programming

Trang 3

Chapter 6: Object-Oriented

Programming

Trang 4

08/13/14 Võ Phương Bình - ITFAC

- DLU

4

Introduction

 Object-Oriented Programming (OOP)

 Inheritance - form of software reusability

 New classes created from existing ones

 Absorb attributes and behaviors, and add in their own

 Override methods - redefine inherited methods

 Subclass inherits from superclass

 Direct superclass - subclass explicitly inherits

 Indirect superclass - subclass inherits from two or more levels up the class hierarchy

Trang 5

Introduction, cont

 Object-Oriented Programming

Introduce protected member access

 Relationships

 "is a" - inheritance

 Object of subclass "is a" object of the superclass

 "has a" - composition

 Object "has a" object of another class as a member

 Class libraries

 New classes can inherit from them

 Someday software may be constructed from standardized, reusable components (like hardware)

 Create more powerful software

Trang 6

 A rectangle "is a" quadrilateral

 Rectangle is a specific type of quadrilateral

 Quadrilateral is the superclass, rectangle is the subclass

 Incorrect to say quadrilateral "is a" rectangle

 Naming can be confusing because subclass has more features than superclass

 Subclass more specific than superclass

 Every subclass "is an" object of its superclass, but not versa

vice- Form tree-like hierarchal structures

Create a hierarchy for class Shape (next slide)

Trang 7

Superclasses and Subclasses, cont

 Using inheritance

Use keyword extends

class TwoDimensionalShape extends Shape{ }

private members of superclass not directly accessible to

subclass

 All other variables keep their member access

Shape

TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron

Trang 8

Intermediate protection between private and public

 Only accessible by methods of superclass, of subclass, or classes in the same package

 Subclass methods

Can refer to public or protected members by name

Overridden methods accessible with super.methodName

Trang 9

Relationship between Superclass

Objects and Subclass Objects

 Object of subclass

 Can be treated as object of superclass

 Reverse not true

 Suppose many classes inherit from one superclass

 Can make an array of superclass references

 Treat all objects like superclass objects

Trang 10

 Subclass can redefine superclass method

 When method mentioned in subclass, subclass version used

Access original superclass method with super.methodName

 To invoke superclass constructor explicitly (called implicitly by

default)

super(); //can pass arguments if needed

 If called explicitly, must be first statement

 Every Applet has used these techniques

 Inheritance concept formalized

Java implicitly uses class Object as superclass for all classes

We have overridden init and paint when we extended JApplet

Trang 11

1 // Fig 27.3: Point.java

2 // Definition of class Point

3

4 public class Point {

5 protected int x, y; // coordinates of the Point

21 // Set x and y coordinates of Point

22 public void setPoint( int a, int b )

Trang 12

08/13/14 Võ Phương Bình - ITFAC - DLU 12

1.2 Methods

-1 Circle Definition 1.1 extends Point 1.2 Multiple constructors

38 // Fig 27.3: Circle.java

39 // Definition of class Circle

40

41 public class Circle extends Point { // inherits from Point

42 protected double radius;

58 // Set radius of Circle

59 public void setRadius( double r )

60 { radius = ( r >= 0.0 ? r : 0.0 ); }

31 // get y coordinate

32 public int getY() { return y; }

33

34 // convert the point into a String representation

35 public String toString()

36 { return "[" + x + ", " + y + "]"; }

37 }

37 }

Trang 13

62 // Get radius of Circle

63 public double getRadius() { return radius; }

64

65 // Calculate area of Circle

66 public double area() { return Math.PI * radius * radius; }

67

68 // convert the Circle to a String

69 public String toString()

Trang 14

08/13/14 Võ Phương Bình - ITFAC - DLU 14

80 public class InheritanceTest {

81 public static void main( String args[] )

93 // use the "is a" relationship to refer to a Circle

94 // with a Point reference

95 pointRef = c; // assign Circle to pointRef

96

97 output += "\n\nCircle c (via pointRef): " +

98 pointRef.toString();

99

100 // Use downcasting (casting a superclass reference to a

101 // subclass data type) to assign pointRef to circleRef

102 circleRef = (Circle) pointRef;

103

104 output += "\n\nCircle c (via circleRef): " +

105 circleRef.toString();

Trang 15

107 DecimalFormat precision2 = new DecimalFormat( "0.00" );

108 output += "\nArea of c (via circleRef): " +

109 precision2.format( circleRef.area() );

110

111 // Attempt to refer to Point object

112 // with Circle reference

113 if ( p instanceof Circle ) {

114 circleRef = (Circle) p; // line 40 in Test.java

115 output += "\n\ncast successful";

116 }

117 else

118 output += "\n\np does not refer to a Circle";

119

120 JOptionPane.showMessageDialog( null , output,

121 "Demonstrating the \"is a\" relationship",

Trang 16

08/13/14 Võ Phương Bình - ITFAC - DLU 16

Program Output

Trang 17

Implicit Superclass-Object Conversion

Subclass-Object-to- References to subclass objects

 May be implicitly converted to superclass references

 Makes sense - subclass contains members corresponding to those

of superclass

 Referring to a subclass object with a superclass reference

 Allowed - a subclass object "is a" superclass object

 Can only refer to superclass members

 Referring to a superclass object with a subclass reference

 Error

 Must first be cast to a superclass reference

 Need way to use superclass references but call subclass

methods

Discussed later in the chapter

Trang 18

 "has a" relationship

members

Employee “is a” BirthDate; //Wrong!

Employee “has a” Birthdate; //Composition

Trang 19

Introduction to Polymorphism

 Little or no modification required

 Only parts of program that need direct knowledge of new class must be changed

Trang 20

08/13/14 Võ Phương Bình - ITFAC

- DLU

20

Dynamic Method Binding

 Dynamic Method Binding

 At execution time, method calls routed to appropriate

version

 Method called for appropriate class

 Example

Triangle, Circle, and Square all subclasses of Shape

Each has an overridden draw method

Call draw using superclass references

 At execution time, program determines to which class the reference is actually pointing

Calls appropriate draw method

Trang 21

final Methods and Classes

Declaring variables final

 Indicates they cannot be modified after declaration

 Must be initialized when declared

Declaring methods final

 Cannot be overridden in a subclass

static and private methods are implicitly final

Program can inline final methods

 Actually inserts method code at method call locations

 Improves program performance

Declaring classes final

 Cannot be a superclass (cannot inherit from it)

All methods in class are implicitly final

Trang 22

 Abstract classes (abstract superclasses)

 Sole purpose is to be a superclass

 Other classes inherit from it

 Cannot instantiate objects of an abstract class

 Can still define constructor

 Too generic to define real objects

Declare class with keyword abstract

 Concrete class

 Can instantiate objects

 Provide specifics

 Class hierarchies

Most general classes are usually abstract

TwoDimensionalShape - too generic to be concrete

Trang 23

Polymorphism Example

Class Quadrilateral

Rectangle "is a" Quadrilateral

getPerimeter method can be performed on any subclass

Square, Parallelogram, Trapezoid

 Same method takes on "many forms" - polymorphism

 Have an array of superclass references

 Array would point to all the objects

Call getPerimeter using the references

 Appropriate method called for each class

 Adding a new subclass

Simply need to define getPerimeter for that class

 Can refer to it with superclass reference

 Can use same superclass array as before - "fits right in"

Trang 24

 New classes can be added easily

 One method call can cause different actions to occur,

depending on object receiving call

 References

Can create references to abstract classes

Cannot instantiate objects of abstract classes

Keyword abstract

Any class with an abstract method must be abstract

abstract methods must be overridden in subclass

Otherwise, subclass must be abstract

Trang 25

Polymorphism Example, cont

(such as an array)

 Walk through an array of superclass references

Call draw method for each reference

Trang 26

at compile time

with object

Trang 27

Inheriting Interface and

Implementation

 Polymorphism example

abstract superclass Shape

Subclasses Point, Circle, Cylinder

Class Shape used to define a set of common methods

 Interface is the three common methods

Implementation of area and volume used for first levels of

hierarchy

Create an array of Shape references

 Point them to various subclass objects

Call methods through the Shape reference

Trang 28

08/13/14 Võ Phương Bình - ITFAC - DLU 28

1 // Fig 27.4: Shape.java

2 // Definition of abstract base class Shape

3

4 public abstract class Shape extends Object {

5 public double area() { return 0.0; }

6 public double volume() { return 0.0; }

7 public abstract String getName();

8 }

Trang 29

08/13/14 Võ Phương Bình - ITFAC - DLU 29

Class Point

1 point inherits from Shape

1.1 protected data members

1.2 Constructors 1.3 New methods

9 // Fig 27.4: Point.java

10 // Definition of class Point

11

12 public class Point extends Shape {

13 protected int x, y; // coordinates of the Point

21 // Set x and y coordinates of Point

22 public void setPoint( int a, int b )

34 // convert the point into a String representation

35 public String toString()

36 { return "[" + x + ", " + y + "]"; }

37

38 // return the class name

39 public String getName() { return "Point"; }

40 }

40 }

Trang 30

08/13/14 Võ Phương Bình - ITFAC - DLU 30

Class Circle

1 Inherits from point 1.1 protected data member

1.2 Constructors 1.3 New methods 1.4 Overridden method area

41 // Fig 27.10: Circle.java

42 // Definition of class Circle

43

44 public class Circle extends Point { // inherits from Point

45 protected double radius;

61 // Set radius of Circle

62 public void setRadius( double r )

63 { radius = ( r >= 0 ? r : 0 ); }

64

65 // Get radius of Circle

66 public double getRadius() { return radius; }

67

68 // Calculate area of Circle

69 public double area() { return Math.PI * radius * radius; }

70

Trang 31

71 // convert the Circle to a String

72 public String toString()

73 { return "Center = " + super.toString() +

74 "; Radius = " + radius; }

75

76 // return the class name

77 public String getName() { return "Circle"; }

78 }

78 }

Trang 32

08/13/14 Võ Phương Bình - ITFAC - DLU 32

Class Cylinder

1 inherit from Circle 1.1 protected data member

1.2 Constructors 1.3 New methods 1.4 Overridden method area

79 // Fig 27.10: Cylinder.java

80 // Definition of class Cylinder

81

82 public class Cylinder extends Circle {

83 protected double height; // height of Cylinder

99 // Set height of Cylinder

100 public void setHeight( double h )

101 { height = ( h >= 0 ? h : 0 ); }

102

103 // Get height of Cylinder

104 public double getHeight() { return height; }

105

106 // Calculate area of Cylinder (i.e., surface area)

107 public double area()

108 {

109 return 2 * super.area() +

110 2 * Math.PI * radius * height;

Trang 33

111 }

112

113 // Calculate volume of Cylinder

114 public double volume() { return super.area() * height; }

115

116 // Convert a Cylinder to a String

117 public String toString()

118 { return super.toString() + "; Height = " + height; }

119

120 // Return the class name

121 public String getName() { return "Cylinder"; }

122 }

122 }

Trang 34

08/13/14 Võ Phương Bình - ITFAC - DLU 34

Driver

1 import 1.1 Initialize objects 1.2 Create Shape array

128 public class Test {

129 public static void main( String args[] )

130 {

131 Point point = new Point( 7, 11 );

132 Circle circle = new Circle( 3.5, 22, 8 );

133 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 );

Trang 35

2.1 Call methods using array of

155 // Loop through arrayOfShapes and print the name,

156 // area, and volume of each object.

157 for ( int i = 0; i < arrayOfShapes.length; i++ ) {

Trang 36

08/13/14 Võ Phương Bình - ITFAC - DLU 36

Program Output

Trang 37

Creating and Using Interfaces

 Interface

Keyword interface

Has set of public abstract methods

Can contain public final static data

 Using interfaces

Class specifies it uses interface with keyword implements

 Multiple interfaces use comma-separated list

Class must define all abstract methods in interface

 Must use same number of arguments, same return type

 Using interface like signing a contract

 "I will define all methods specified in the interface"

 Same "is a" relationship as inheritance

Trang 38

 Using interfaces (continued)

Interfaces used in place of abstract classes

 Used when no default implementation

Typically public data types

Interface defined in its own java file

 Interface name same as file name

 Previous interfaces

We have used interface ActionListener

Required to define actionPerformed

 Reexamine previous hierarchy

Replace abstract class Shape with interface Shape

Trang 39

1 // Fig 27.5: Shape.java

2 // Definition of interface Shape

3

4 public interface Shape {

5 public abstract double area();

6 public abstract double volume();

7 public abstract String getName();

8 }

8 }

Trang 40

08/13/14 Võ Phương Bình - ITFAC - DLU 40

Class Point

1 inherits from Object 1.1 implements Shape 1.2 protected data members

1.3 Constructors 1.4 New methods

1.5 Define method area

(required)

9 // Fig 27.5: Point.java

10 // Definition of class Point

11

12 public class Point extends Object implements Shape {

13 protected int x, y; // coordinates of the Point

21 // Set x and y coordinates of Point

22 public void setPoint( int a, int b )

34 // convert the point into a String representation

35 public String toString()

36 { return "[" + x + ", " + y + "]"; }

37

38 // return the area

39 public double area() { return 0.0; }

40

Trang 41

41 // return the volume

42 public double volume() { return 0.0; }

43

44 // return the class name

45 public String getName() { return "Point"; }

46 }

46 }

Trang 42

08/13/14 Võ Phương Bình - ITFAC - DLU 42

4 public class Circle extends Point { // inherits from Point

5 protected double radius;

21 // Set radius of Circle

22 public void setRadius( double r )

23 { radius = ( r >= 0 ? r : 0 ); }

24

25 // Get radius of Circle

26 public double getRadius() { return radius; }

27

28 // Calculate area of Circle

29 public double area() { return Math.PI * radius * radius; }

30

Ngày đăng: 11/08/2014, 22:23

TỪ KHÓA LIÊN QUAN