Object Oriented Programming. Problem Description “ …customers are allowed to have different...

44
Object Oriented Programming

Transcript of Object Oriented Programming. Problem Description “ …customers are allowed to have different...

Page 1: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Object Oriented Programming

Page 2: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Problem Description

“ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and transfer money between accounts”

Page 3: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Procedural Approach

bool MakeDeposit(int accountNum,float amount);float Withdraw(int accountNum,float amount);

struct Account {char *name;int accountNum;float balance;char accountType;

};

Page 4: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Procedural Approach cont’d

Focus is on proceduresAll data is shared: no protectionMore difficult to modifyHard to manage complexity

Page 5: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Procedural vs. Object-Oriented

Procedural

Withdraw, deposit, transfer

Object Oriented

Customer, money, account

Page 6: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Mapping the world to software

Objects in the problem domain are mapped to objects in software

011101

10011

11101

0110100

11010

010101

1110101

10101

Page 7: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Object Oriented

Data and operations are grouped together

AccountWithdraw

Deposit

Transfer

Interface:

Set of available operations

Page 8: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Data Encapsulation

class Account {

private float balance;

public float withdraw();

public void deposit(float amount);

}

Page 9: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Advantages of Encapsulation

Protection Consistency Allows change

Page 10: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Objects and Classes

Classes reflect concepts, objects reflect instances that embody those concepts.

AvaSummer HenriettaJazzlyn

girlclassobject

Page 11: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Objects and Classes cont’d

A class captures the common properties of the objects instantiated from itA class characterizes the common behavior of all the objects that are its instances

Page 12: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Objects and Classes cont’dClass BankAccountBalanceInterestYTDOwnerAccount_number

Balance 500InterestYTDOwner Account_number

Balance 10,000InterestYTDOwner Account_number

Operations

MakeDesposit

Transfer

WithDraw

GetBalance

Page 13: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Objects as instances of Classes

The world conceptually consists of objectsMany objects can be said to be of the same type or class My bank account, your bank account, Bill

Gates’ bank account …

We call the object type a class

Page 14: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Instantiation

An Object is instantiated from a ClassBankAccount myAccount;

myAccount = new BankAccount();

Page 15: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Objects and Classes

Class Visible in

source code The code is not

duplicated

Object Own copy of

data Active in

running program

Occupies memory

Has the set of operations given in the class

Page 16: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Classification

Mammal

Rodent Primate Cat

Reptile

Animal

SquirrelMouse

Page 17: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Classification

                             

                                       

   

Enjoy a variety of personal banking options from First American. The following outlines a number of First American products. If you have any questions, please visit any First American Branch or contact us.

Checking • Bank a lot without spending a lot: ValueFirst® Checking. • Few checks and prefer PC Banking or ATMs: Select Access. • Earn interest on checking dollars: First Interest Checking • You are 55 years or better: 55 & Better Silver • Premium checking features with higher interest rates than a personal checking account:

First American Platinum Checking • Write less than 10 checks per month, or bank through an ATM: Budget Checking. • Younger than 24 years old and in school: Student Checking • Less than 20 transactions per month (excluding ATM, POS, and CheckCard): First Account • Make the most out of every dollar: Tailored Money Sweep

Page 18: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Classification

Checking Account

Value First Select Access First Interest

Savings Account

Account

Page 19: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Inheritance

A class which is a subtype of a more general class is said to be inherited from it.The sub-class inherits the base class’ data members and member functions

Page 20: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Inheritance cont’d

A sub-class has all data members of its base-class plus its ownA sub-class has all member functions of its base class (with changes) plus its ownInheritance is meant to implement sub-typing (don’t abuse it)

Page 21: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Abstraction

Management of complexityHierarchical classification:

is-a relationship: inheritancehas-a relationship: containment

Page 22: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Polymorphism

One interface Multiple implementations Inheritance Method overloading

Page 23: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

What is a good class ?

A class abstracts objects A class should be non-trivial in the context of the program (has data structures and operations different from other classes)

Page 24: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Summary

What is Object Oriented Programming?Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of one or more hierarchy of classes united via inheritance relationships

Page 25: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Lecture 2:Object Oriented Programming I

Page 26: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Procedural vs. Object-Oriented Programming

The unit in procedural programming is function, and unit in object-oriented programming is class

Procedural programming concentrates on creating functions, while object-oriented programming starts from isolating the classes, and then look for the methods inside them.

Procedural programming separates the data of the program from the operations that manipulate the data, while object-oriented programming focus on both of them

figure1: procedural figure2: object-oriented

Page 27: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Concept of Class and Object

“Class” refers to a blueprint. It defines the variables and methods the objects support

“Object” is an instance of a class. Each object has a class which defines its data and behavior

Page 28: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Class MembersA class can have three kinds of members: fields: data variables which determine the

status of the class or an object methods: executable code of the class

built from statements. It allows us to manipulate/change the status of an object or access the value of the data member

nested classes and nested interfaces

Page 29: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Sample classclass Pencil {

public String color = “red”;public int length;public float diameter;

public void setColor (String newColor) { color = newColor;}

}

Page 30: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Fields – DeclarationField Declaration a type name followed by the field name, and

optionally an initialization clause primitive data type vs. Object reference

boolean, char, byte, short, int, long, float, double field declarations can be preceded by different

modifiers access control modifiers static final

Page 31: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

More about field modifiers (1) Access control modifiers private: private members are accessible only

in the class itself package: package members are accessible in

classes in the same package and the class itself

protected: protected members are accessible in classes in the same package, in subclasses of the class, and in the class itself

public: public members are accessible anywhere the class is accessible

Page 32: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

public class Pencil {public String color = “red”;public int length;public float diameter;private float price;

public static long nextID = 0;

public void setPrice (float newPrice) {

price = newPrice;}

}

public class CreatePencil {public static void main (String args[]){

Pencil p1 = new Pencil();p1.price = 0.5f;

}}

Pencil.java

CreatePencil.java

%> javac Pencil.java%> javac CreatePencil.javaCreatePencil.java:4: price has private access in Pencil

p1.price = 0.5f; ^

Page 33: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

More about field modifiers (2)static only one copy of the static field exists, shared

by all objects of this class can be accessed directly in the class itself access from outside the class must be

preceded by the class name as followsSystem.out.println(Pencil.nextID);

or via an object belonging to the class from outside the class, non-static fields must

be accessed through an object reference

Page 34: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

public class CreatePencil {public static void main (String args[]){

Pencil p1 = new Pencil();Pencil.nextID++;System.out.println(p1.nextID);//Result?

Pencil p2 = new Pencil();Pencil.nextID++;System.out.println(p2.nextID);//Result?

System.out.println(p1.nextID);//Result?

}}

1

still 2!

2

Note: this code is only for the purpose of showing the usage of static fields. It has POOR design!

Page 35: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

More about field modifiers (3)

final once initialized, the value cannot be changed often be used to define named constants static final fields must be initialized when the

class is initialized non-static final fields must be initialized when

an object of the class is constructed

Page 36: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Fields –Initialization

Field initialization not necessary to be constants, as long as

with the right type If no initialization, then a default initial value

is assigned depending on its type

Type Initial Valueboolean falsechar ‘\u0000’byte, short, int, long 0float +0.0fdouble +0.0object reference null

Page 37: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Methods – DeclarationMethod declaration: two parts

1. method header consists of modifiers (optional), return type, method

name, parameter list and a throws clause (optional) types of modifiers

access control modifiers abstract

the method body is empty. E.g. abstract void sampleMethod( );

static represent the whole class, no a specific object can only access static fields and other static methods of

the same class final

cannot be overridden in subclasses

2. method body

Page 38: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Methods – InvocationMethod invocations invoked as operations on objects/classes using

the dot ( . ) operator

reference.method(arguments) static method:

Outside of the class: “reference” can either be the class name or an object reference belonging to the class

Inside the class: “reference” can be ommitted

non-static method: “reference” must be an object reference

Page 39: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Method - OverloadingA class can have more than one method with the same name as long as they have different parameter list.

public class Pencil {. . .public void setPrice (float newPrice) {

price = newPrice;}

public void setPrice (Pencil p) {price = p.getPrice(); }

}

How does the compiler know which method you’re invoking? — compares the number and type of the parameters and uses the matched one

Page 40: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Methods – Parameter ValuesParameters are always passed by value.

public void method1 (int a) { a = 6;}

public void method2 ( ) { int b = 3; method1(b); // now b = ?

// b = 3}

When the parameter is an object reference, it is the object reference, not the object itself, getting passed.

Haven’t you said it’s passed by value, not reference ?

Page 41: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

class PassRef{public static void main(String[] args) { Pencil plainPencil = new Pencil("PLAIN"); System.out.println("original color: " + plainPencil.color);

paintRed(plainPencil);

System.out.println("new color: " + plainPencil.color);}

public static void paintRed(Pencil p) { p.color = "RED"; p = null;}

}

another example: (parameter is an object reference)

plainPencil

plainPencil

plainPencil p

plainPencil p

color: PLAIN

- If you change any field of the object which the parameter refers to, the object is changed for every variable which holds a reference to this object

color: PLAIN

color: RED

color: RED

NULL

p

- You can change which object a parameter refers to inside a method without affecting the original reference which is passed

- What is passed is the object reference, and it’s passed in the manner of “PASSING BY VALUE”!

Page 42: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

The Main Method - Concept

main method the system locates and runs the main method

for a class when you run a program other methods get execution when called by

the main method explicitly or implicitly must be public, static and void

Page 43: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

The Main Method - Getting Input from the Command Line

When running a program through the java command, you can provide a list of strings as the real arguments for the main method. In the main method, you can use args[index] to fetch the corresponding argument

class Greetings { public static void main (String args[]){

String name1 = args[0]; String name2 = args[1]; System.out.println("Hello " + name1 + “&“

+name2); }

}

java Greetings Jacky MaryHello Jacky & Mary

Note: What you get are strings! You have to convert them into other types when needed.

Page 44: Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.

Modifiers of the classesA class can also has modifiers

public publicly accessible without this modifier, a class is only accessible within its own

package abstract

no objects of abstract classes can be created all of its abstract methods must be implemented by its

subclass; otherwise that subclass must be declared abstract also

final can not be subclassed

Normally, a file can contain multiple classes, but only one public one. The file name and the public class name should be the same