ece 462 object-oriented programming using c++ and … · ece 462 object-oriented programming using...

168
ECE 462 Object-Oriented Programming using C++ and Java Program Structure Yung-Hsiang Lu [email protected]

Upload: phungbao

Post on 15-Apr-2018

241 views

Category:

Documents


3 download

TRANSCRIPT

ECE 462Object-Oriented Programming

using C++ and Java

Program Structure

Yung-Hsiang [email protected]

YHL Program Structure 2

Objects and Classes

• Organize objects with similar properties (attributes and behaviors) into classes: human, car, computer, phone, window, circle, rectangle, triangle, bridge, skyscraper ...

• Inheritance: find commonality among classes (not objects) and create a base class that represents the common interfaces and behavior

• Common interface of Shape:– color– line style and thickness– area but it is computed

differently in each derived class

Shape

Circle

Triangle

Rectangle

YHL Program Structure 3

Reuse (Base or Derived?)

• Attribute (member data)– If an attribute is shared by all derived classes, the attribute

should be declared in the base class. example: color, line style, thickness.

– If an attribute is unique to a class, it should be declared in this derived class, example: radius for circle.

• Behavior (member function, method):– If a method is available to all derived classes, such as getArea

and setLineStyle, it should be declared in the base class.– If the method’s implementation is applicable to all derived

classes, it should be implemented in the base class.– If the implementation is unique to each derived class, it should

be implemented in the derived classes.

Generate Code fromUML Class Diagram

YHL Program Structure 5

Use Netbeans• to draw a UML class diagram• to generate code.

YHL Program Structure 6

YHL Program Structure 7

YHL Program Structure 8

YHL Program Structure 9

YHL Program Structure 10

YHL Program Structure 11

YHL Program Structure 12

YHL Program Structure 13

YHL Program Structure 14

YHL Program Structure 15

C++: string (lower case)Java: String (upper case)

Both languages are case sensitive

YHL Program Structure 16

name of class

YHL Program Structure 17

attributes

behaviors(functions,operations)

YHL Program Structure 18

YHL Program Structure 19

YHL Program Structure 20

YHL Program Structure 21

YHL Program Structure 22

YHL Program Structure 23

YHL Program Structure 24

YHL Program Structure 25

YHL Program Structure 26

YHL Program Structure 27

YHL Program Structure 28

YHL Program Structure 29

base / derived classes

Generate Java Codefrom Class Diagram

YHL Program Structure 31

YHL Program Structure 32

Open a Java project so that Netbeans can generate code from the UML diagram

YHL Program Structure 33

YHL Program Structure 34

YHL Program Structure 35

YHL Program Structure 36

YHL Program Structure 37

YHL Program Structure 38

YHL Program Structure 39

YHL Program Structure 40

YHL Program Structure 41

YHL Program Structure 42

YHL Program Structure 43

YHL Program Structure 44

YHL Program Structure 45

YHL Program Structure 46

C++ and Java Syntax

class Student extends Person class Student: public Person

final String p_lastName;const string p_lastName;

public class Person {public Person(String ln, String fn)

{

class Person{public:

Person(string ln, string fn);

p1.print();p1.print();

Person p1 = new Person("Johnson", "Tom");

Person p1("Johnson", "Tom");

public static void main(String[] args) {

int main(int argc, char * argv[])

Javac++

YHL Program Structure 47

main alwaysinside a class

Creating an object must use new.

main has only one parameter

Java

YHL Program Structure 48

main always outside a class

Creating an object does not use new.(C++ can also use new to create anobject; this will be discussed later.)

main has two parametersC++

YHL Program Structure 49

Encapsulation

• Both C++ and Java provide three levels of protection:– private (default), accessible to only the class– protected, accessible to the class and its derived

classes– public, no restriction

• The three protection levels apply to both attributes (also called member data) and functions (also called member function or methods)

• In general, keep as many attributes and functions private as possible. Allow only limited accesses.

YHL Program Structure 50

JavaString (uppercase)

public function

public return-type function

no return-type for constructorno header file for Javano destructorno virtual

System.out.println to print

YHL Program Structure 51

C++

string (lowercase)

public:

no return-type for constructor

destructor, no return type, virtual

YHL Program Structure 52

C++

line break

initialization

cout to print

YHL Program Structure 53

Javaextends for derived class

super for base class constructor

super for base class function

YHL Program Structure 54

C++

public: for derived class

YHL Program Structure 55

class name for base class constructor

class name for base class function

C++

YHL Program Structure 56

What is Method / Message

• A message is a request to an object to do something. An object can receive a message if it is declared as a method in a base class or the corresponding class.

• In OOP, many objects are created and they interact by “sending messages”, for example,– A Driver object sends a message “accelerate” to a

MotorVehicle object.– An Instructor object sends a message

“submitHomework” to a Student object.– A Caller object sends a message “callNumber” to a

MobilePhone object.

YHL Program Structure 57

Message

• not a network concept• the mechanism to interact with an object

– ask a bridge about its length (no parameter)– turn on a light (no parameter)– accelerate a car (parameter = acceleration, m/s2)– add a customer to a database (parameter =

customer)– ask a customer of the credit number

• Disallowed messages are checked at compile time: compiler error if you ask a light bulb to accelerate.

YHL Program Structure 58

• A Driver object (dobj) sends an “accelerate” message to a Car object (cobj)⇒ cobj.accelerate();

• A Teacher object (tobj) sends a message to a Student object (sobj) to submit a Homework object (hobj)⇒ sobj.submit(hobj);

• A Person object (pobj) sends a Light Bulb object (bobj) message to turn on⇒ bobj.on();

The object is the recipient of the message. Where is the sender? It is implicit by the location of the message.

YHL Program Structure 59

a Person object canaccept "print" message

YHL Program Structure 60

sent a print message to a Person object

Common Mistakes

YHL Program Structure 62

A local variable has the same name as an attribute

YHL Program Structure 63

A local variable has the same name as an attribute

remove final

name not initialized

YHL Program Structure 64

object declared but not created (in Java)

YHL Program Structure 65

Self Test

ECE 462Object-Oriented Programming

using C++ and Java

Class Examples

Yung-Hsiang [email protected]

YHL Class Examples 2

Class Hierarchy

class name, usually noun

YHL Class Examples 3

Overloaded Constructors

overload = several functionswith the same name but different parameters

constructor = function of thesame name as the class

YHL Class Examples 4

encapsulation level

return type

methods usually verbs

YHL Class Examples 5

inheritance

YHL Class Examples 6

C++

inheritance

class name, usually noun

YHL Class Examples 7

attributes

YHL Class Examples 8

attributes from immediate base class

YHL Class Examples 9

methods usually verbs

YHL Class Examples 10

methods usually verbs

YHL Class Examples 11

methods usually verbs

YHL Class Examples 12

Naming Convention

• class name: noun, capitalize first letter • attribute name: noun, lower case• method name: verb, lower case, followed by upper case

YHL Class Examples 13

Self Test

ECE 462Object-Oriented Programming

using C++ and Java

Encapsulation and Polymorphism

Yung-Hsiang [email protected]

YHL Encapsulation and Polymorphism 2

Implementation Independent

• If you ask a student for ID, do you care how the student finds the answer?– the student may remember the ID– the student may check the student's ID card– the student may call the department office and ask– the student may call a roommate– ...

• For you, these methods are the same. You obtain the ID number of the student.

• You do not need to know how the student implementsthe method to respond to your question.

YHL Encapsulation and Polymorphism 3

Interface vs Implementation

• Suppose you are creating a program to manage books in a library.– When the library has only hundreds of books, you can

use a list to store each book (author, title, year ...)– As the number of books grows, you may need to use

a more sophisticated indexing scheme or SQL ....• The library provides the same interface to search books.• Users should not feel any difference about the different

implementations.• Encapsulation is enforced by compilers (no run-time

surprises).

YHL Encapsulation and Polymorphism 4

Interface

• A class' public attributes and methods form the interface for the objects of this class and all derived classes.

• If func is a public method, the object must be able to respond to a call of func. This is a "promise".

• Code reuse ⇒ A promise cannot be withdrawn.• Anything that is not in the interface (private attributes

and methods) can be changed without affecting any code using the class.

⇒ The program is easier to maintain and reuse.• Keep an interface as small as possible. Make only the

essential functionalities visible. Hide all details.

YHL Encapsulation and Polymorphism 5

Why Encapsulation?

• prevent accidental modification of objects' attributes• hide implementation details• keep data consistency (some attributes must be

changed simultaneously)• reduce the amount of code to maintain (since the details

are hidden, they will not affect the users of the code)• success of OOP

– large libraries for many functionalities– these libraries can be improved without breaking the

users' code

YHL Encapsulation and Polymorphism 6

Cannot change last name.

The phone number canbe changed.

C++

YHL Encapsulation and Polymorphism 7

YHL Encapsulation and Polymorphism 8

add a private attribute

YHL Encapsulation and Polymorphism 9

change constructor and print

YHL Encapsulation and Polymorphism 10

Student::print can access last and first names

no error

YHL Encapsulation and Polymorphism 11

error

Polymorphism

YHL Encapsulation and Polymorphism 13

p1 = s1 allowedA Student object is alwaysa Person object.

Java

YHL Encapsulation and Polymorphism 14

p1.print() behaves as a Studentobject, even though p1 is declaredas a Person object

YHL Encapsulation and Polymorphism 15

s1 = p1 not allowedA Person object is notnecessarily a Student object.

YHL Encapsulation and Polymorphism 16

ErrorDNN

ErrorBNN

DDerivedYN

ErrorBaseYN

BDNY

BBNY

DerivedDerivedYY

BaseBaseYY

ExecuteObjectDerivedBase

YHL Encapsulation and Polymorphism 17

Polymorphism

BaseClass obj1 = new BaseClass( ... );obj1.method(); // call baseDerivedClass obj2 = new DerivedClass( ... );obj2.method(); // call derived (if available)obj1 = obj2; // no problemobj1.method(); // call derived (if available)obj2 = obj1; // error

YHL Encapsulation and Polymorphism 18

Virtual Function in C++

• In Java, all functions are "virtual" and polymorphism is always supported.

• In C++, polymorphism is not enabled by default.• A function is polymorphic only if it is declared virtual at

the base class and the object is created by new.ClassName * obj = new ClassName(parameters);ClassName * obj = new ClassName; // no parameter

• Once a function is virtual, it is virtual for all derivedclasses.

• If a derived class can use the same method (implementation), do not override the method.

YHL Encapsulation and Polymorphism 19

Virtual in C++

• All virtual methods must have the same prototype (i.e. return type and argument types).

• virtual ⇒ derived class may (not have to) override• not virtual ⇒ should not override, compiler will allow, but

don’t ask for trouble• why virtual in C++? slightly better performance for non-

virtual ... but ... cause too much confusion • In general, functions in C++ should be virtual unless

you have strong reasons (and know what you are doing)• Constructors are naturally virtual. Destructors should

always be virtual (more about this later).

YHL Encapsulation and Polymorphism 20

overloaded functionsare actually differentfunctions

YHL Encapsulation and Polymorphism 21

YHL Encapsulation and Polymorphism 22

YHL Encapsulation and Polymorphism 23

YHL Encapsulation and Polymorphism 24

YHL Encapsulation and Polymorphism 25

YHL Encapsulation and Polymorphism 26

YHL Encapsulation and Polymorphism 27

Polymorphism is determined at "run-time"

YHL Encapsulation and Polymorphism 29

YHL Encapsulation and Polymorphism 30

YHL Encapsulation and Polymorphism 31

YHL Encapsulation and Polymorphism 32

YHL Encapsulation and Polymorphism 33

YHL Encapsulation and Polymorphism 34

YHL Encapsulation and Polymorphism 35

no polymorphism if the objectis created without using new

YHL Encapsulation and Polymorphism 36

Self Test

ECE 462Object-Oriented Programming

using C++ and Java

Constructor and Destructor (C++)

Yung-Hsiang [email protected]

YHL Constructor and Destructor 2

Constructor (both C++ and Java)

• same name as the class' name (case sensitive)• no return type• usually public• often overloaded• usually create attribute objects by calling new• "naturally" virtual (C++)

YHL Constructor and Destructor 3

YHL Constructor and Destructor 4

JLabel constructor overloaded

YHL Constructor and Destructor 5

Constructors are usually public.

YHL Constructor and Destructor 6

YHL Constructor and Destructor 7

QLabel constructor overloaded, public

YHL Constructor and Destructor 8

Object Creation

• Java:ClassName obj = new ClassName(parameters);

• C++ClassName obj(parameters);

orClassName * obj = new ClassName(parameters);

• In C++ and Java, a class is also a type (similar to int, char, or float).

notice *

YHL Constructor and Destructor 9

"new" = Memory Allocation

• In Java, unused memory will be automatically reclaimed (called garbage collection).

AClass x1 = new AClass( 10, 100 ); x1 = new AClass( 20, 200 );

• It is unnecessary to worry about the objects that cannot be reached. Java reclaims the memory.

• You have to remove all references to the object.• Too much garbage, however, degrades performance.

10, 100x1

20, 200

garbage

YHL Constructor and Destructor 10

C++ Memory Leak

• In C++, unreachable memory is lost, "memory leak".

AClass * x1 = new AClass( 10, 100 ); // x1 is a pointerx1 = new AClass( 20, 200 );

• To prevent memory leakdelete x1;

• Do not use malloc / free in C++. They do not call the constructor / destructor.

10, 100x1

20, 200

leak

YHL Constructor and Destructor 11

new - delete

• If an object is created by calling "new", it should be removed by calling "delete".

AClass * x1 = new AClass( 10, 100 );delete x1;

• new – delete pair– call delete only if new is called earlier– in the same level (not necessarily the same function)– an object can be deleted only once

• use “valgrind --tool=memcheck --leak-check=yes executable” to check memory leak

YHL Constructor and Destructor 12

Memory Leak

• If allocated memory is not reclaimed, the program will gradually run out of memory and eventually crash.

• Memory leak is hard to detect by running the program– usually leak a small amount each time– can take hours, days, or weeks to run out of memory– sometime mistaken as performance problems

• In Java, if an object is no longer needed, remove all references to the object. It will be garbage collected.

• In C++, if an object is no longer needed and the object is created by calling new, delete the object.

YHL Constructor and Destructor 13

YHL Constructor and Destructor 14

YHL Constructor and Destructor 15

YHL Constructor and Destructor 16

Destructor (C++ only)

• add ~ in front of the class' name• no return type• usually public• cannot take parameters ⇒ cannot be overloaded• usually symmetric to constructor• remove attribute objects by calling delete (if they are

created by calling new)• should always be virtual

YHL Constructor and Destructor 17

Calling Order in Class Hierarchy

• In both C++ and Java– the constructor of the base class is called first– the constructor of the derived class is called later⇒ Constructors are naturally virtual because the

constructor in the derived class is always called.⇒ C++ cannot add virtual in front of a constructor.

• In C++– the destructor of the derived class is called first– the destructor of the base class is called later⇒ need to add virtual to ensure the derived class'

destructor is called

YHL Constructor and Destructor 18

Constant Attributes

• Constant attributes must be initialized in constructors.• C++

const type attributeName;constructor(...): attributeName(value) {

...}

• Javafinal type attributeName;⇒ assign value in constructor

YHL Constructor and Destructor 19

YHL Constructor and Destructor 20

YHL Constructor and Destructor 21

overloaded constructor

YHL Constructor and Destructor 22

YHL Constructor and Destructor 23

YHL Constructor and Destructor 24

YHL Constructor and Destructor 25

YHL Constructor and Destructor 26

YHL Constructor and Destructor 27

base constructor first

base destructor second

YHL Constructor and Destructor 28

objects automatically destroyed

destructor not called, memory leak

YHL Constructor and Destructor 29

YHL Constructor and Destructor 30

YHL Constructor and Destructor 31

YHL Constructor and Destructor 32

leak detected

YHL Constructor and Destructor 33

YHL Constructor and Destructor 34

no leak

YHL Constructor and Destructor 35

Derived1's constructor called

Derived1's destructor called

YHL Constructor and Destructor 36

destructor not virtual

YHL Constructor and Destructor 37

Derived1's constructor called

Derived1's destructor not called⇒ possible memory leak

YHL Constructor and Destructor 38

destructor cannot have parameters

destructor cannot be overloaded

YHL Constructor and Destructor 39

const attribute

YHL Constructor and Destructor 40

const attribute must be initialized in constructor

YHL Constructor and Destructor 41

const attribute cannot be initialized using assignments

YHL Constructor and Destructor 42

const attribute must be initialized using ":"

YHL Constructor and Destructor 43

Java

YHL Constructor and Destructor 44

YHL Constructor and Destructor 45

no need to call super

YHL Constructor and Destructor 46

YHL Constructor and Destructor 47

base constructor first

YHL Constructor and Destructor 48

call super

YHL Constructor and Destructor 49

call super

YHL Constructor and Destructor 50

call constructor(int)

YHL Constructor and Destructor 51

constant (final) must be initialized in constructor

YHL Constructor and Destructor 52

no problem

YHL Constructor and Destructor 53

The final field BaseClass.fValue cannot be assigned

YHL Constructor and Destructor 54

Self Test