74
Object Oriented Programming (OOP) Mohamed Ezz

Object Oriented Programming (OOP)

  • Upload
    ringo

  • View
    74

  • Download
    2

Embed Size (px)

DESCRIPTION

Object Oriented Programming (OOP). Mohamed Ezz. Lecture 1. History and Concept. Programming Techniques.  Unstructured programming Where all implementation in one function Main(){-------}  Procedure programming - PowerPoint PPT Presentation

Citation preview

Page 1: Object Oriented Programming (OOP)

Object Oriented Programming (OOP)

Mohamed Ezz

Page 2: Object Oriented Programming (OOP)

Lecture 1

History and Concept

Page 3: Object Oriented Programming (OOP)

Programming Techniques•  Unstructured programming

Where all implementation in one function Main(){-------}

• Procedure programmingWhere repeated part of code separated in a function e.g. factorial function

• Modular programmingWhere No. of functions become huge, and we need a facility to partition it logically according to business/functionality e.g. all mathematical functions together Where we can load modules that include functions we need only

Page 4: Object Oriented Programming (OOP)

Object Oriented • Class

– We try to simulate human behavior, where– Each person can consider as object has the following attribute/properties e.g.

color, length, weight, name– Each person/object has operations/functions/methods e.g. speak, listen, study,

walk– This template with empty attribute, and applied operations/functions can

consider as class– a set of objects with common attributes and behaviors

• Object– Object is instance of class e.g. person, that has attribute assigned with values e.g. color=3,

length=175, weight=80, name= Mohamed– Each object represented in the memory with its attributes, and reference to created object

e.g. pointer– An object is an instance of a class

Page 5: Object Oriented Programming (OOP)

Class & Object

Page 6: Object Oriented Programming (OOP)

Some OOP Concept

• StateEach object has a state based on values of its attribute 

• MessageObject to object communication where one object speak that return string he speak and the other object listen that get words as input from the other object

• BehaviorEach object has different behaviors according to environment surrounding it e.g. student in the faculty, can be brother/sister in home

Page 7: Object Oriented Programming (OOP)

Messages

Page 8: Object Oriented Programming (OOP)

Lecture 2

Creating your First Class

Page 9: Object Oriented Programming (OOP)

Creating Java classes

• Java designed to be portable, for any type of OS/HW

• And its run using java program e.g. java Point.class

• Java complier (javac) generate a byte code file Point.class where this class not run able without java program

• Java class created in a file named Point.java and

Page 10: Object Oriented Programming (OOP)

Point Classclass Point{ //attributes

int x, int y;//method to access object attributesvoid setX(int xx) { x= xx; }int getX() { return x; }void move(int dx, int dy) { x+= dx; y+=dy; } String toString(){ return "x=" +x + " y="+y; } public static void main(String arg[]){

System.out.println("Hi All"); // as printf//create object like int i, where int is the //class and i is the objectPoint p1 = new Point(); // e.g. char*c;

//c=new char[4] Point p2 = new Point();

p1.setX(1); // point mean belong to objectp1.setY(3);p2.setX(4);p2.setY(5);System.out.println(p1); //explain how its workp1.move(2,2);

}}

Page 11: Object Oriented Programming (OOP)

Lecture 3

Variable & Method DefinitionsConstructor

Main methodPackage

Page 12: Object Oriented Programming (OOP)

Class/object is the focus of OOP

• At design time– Class is the basic programming unit; a program

consists of one or more classes– Programming focuses on

• Defining classes and their properties• Manipulating classes/objects properties and behaviors• Handling objects interactions

• At execution time– Programs are executed through predefined

manipulations and interactions

Page 13: Object Oriented Programming (OOP)

Using Objects

– Object initializationClassName objectName; //object declarationobjectName = new ClassName(); // object creation using a class constructor

– OrClassName objectName = new ClassName();

– ExampleCourse cis3270=new Course();Course cis2010=new Course();

Page 14: Object Oriented Programming (OOP)

Using Member Variables

– Member variable declaration• Declaration is the same as common variables• Any where in a class, outside all methods

– Used within the class• Can be used/referenced anywhere directly (global

variable)– Used with objects

• Using the "." operator and preceded with object name• For example: cis3270.prefix, cis3270.title

Page 15: Object Oriented Programming (OOP)

Defining methods– With a return value (type)– String getCourseInfo()

{ String info=prefix+number+" "+title; return info; //return is required}

– Without a return value (type)void printCourseInfo(){ System.out.println(getCourseInfo()); System.out.println(“# of Sections: "+numberOfSections);}

Page 16: Object Oriented Programming (OOP)

Calling Methods– Within the class

• Called by method name directly– Used with objects or outside the class

• Using the "." operator and preceded with object name• Examples:

– System.out.print( cis3270.getCourseInfo() );– //return value is often used in another

expression/statement– cis3270.addSection();– //void method does not return value, thus can be called

as a single statement.

Page 17: Object Oriented Programming (OOP)

Constructors• Constructors

– Constructor is a special method used for object creation– Course cis3270=new Course();– Default constructor

• A constructor without any parameter• If a programmer doesn’t define any constructor for a class, JRE will implicitly create a default

constructor

• Using Constructor– Defining constructors

ClassName() //no “void” or any other data type{

… }

– Using constructor for default states and behaviors of an object when it is initially created

Page 18: Object Oriented Programming (OOP)

Constructor ExampleClass Date {

int day, month, year; Date (){

day = 13;month= 11;year= 1990;

}orDate (int d, int m, int y){

day = d;month= m;year= y;

}

public static void main (String arg[]){Date today = new Date();

//orDate meeting= new Date(5,11,2009);

}

Page 19: Object Oriented Programming (OOP)

Java OOP Summary– Class/object is the focus of Java programming– Class is the basic programming unit; more complex Java

programs consist of multiple classes (objects) that will interact with each other

– Java programming focuses on designing these classes and their interactions

• Defining classes, their member variables and methods• Creating and using objects• Manipulating object properties through methods• Handling objects interactions (calling other object’s methods)

Page 20: Object Oriented Programming (OOP)

The “main” Method

• Following OOP guidelines, the use of the “main” method should be deemphasized

• The “main” method is merely a starting point of the application• There should not be too many statements in the main method• Using objects and methods effectively

– Typically (and ideally), you only do these things in the main method

• Creating objects• Calling class/object methods

Page 21: Object Oriented Programming (OOP)

Java Packages– Java hierarchically organizes classes into packages*

• java.lang• java.text• java.util• …

– Classes need to be referred using its complete name (package + class name): for example, java.util.Calendar

• Packages can be “imported” to avoid writing package names every time you use a class (except java.lang)

import java.util.*;

Page 22: Object Oriented Programming (OOP)

Package

Date Point

Date Point

Date Point

Second.section1 Second.section2 Second.section3

import second.section1.*; // first approachOr import second.section1.Point; // second approachimport second.section2.Date;

//fourth without any import in classes belong to same packagepublic static void main (String arg[]){Point p1= new Point(); // which classDate d1= new date(); //which classsecond.section1.Date d2 = new second.section1.Date(); // third approach}

Page 23: Object Oriented Programming (OOP)

Using Package• Using Package

– Organizing your classes into packages• A class can only be in one package• No duplicate class definition in the same package• Put the package statement at the beginning• Packages correspond to directories in local file system

– Examples:– package cis3270;– package cis3270.assignment;– package cis3270.lecture.web;

• Default Package– A class without any package defined is in a “default package”– The default package is NOT the root package!

• Classes in the default package cannot be referenced outside the default package

Page 24: Object Oriented Programming (OOP)

Lecture 4

Reference Data typeOverloading

Variable ScopeAccess SpecifierClass Variable Complex Class

Page 25: Object Oriented Programming (OOP)

Reference Data Type

• Reference Data Type• Reference data type stores memory address

(reference) as its value

Page 26: Object Oriented Programming (OOP)

Object Assignment

• Objects are assigned by reference

Page 27: Object Oriented Programming (OOP)

Variable Scope

• Member variable– Something like a global variable within the class

• Local variable– Method parameter– Method level variable– Block level variable

• A variable is effective at its declaration level and all sub-levels

Page 28: Object Oriented Programming (OOP)

Variable Scope

Page 29: Object Oriented Programming (OOP)

Class Variable

• What is the different between member(instant) variable & class variable? Instant Variable Class Variable

Declaration Inside classint x, int y;

Inside class with static keyword int static point_count;

Access Using object p1.x;

Using object or Classp1. point_count;Point. point_count;

Change Value Effected in each object

Effected for all classInitialized in the class

Memory allocation

Separate location for each object

Shared location for all class objects & the class

Page 30: Object Oriented Programming (OOP)

Access Specifier• private

– The variable or method accessed only from inside the class• Member method only

• Default– The variable or method accessed from inside the class and the sister

class inside same package• Member method• Main method• Non-member method belong to classes in the same package

• public – The variable or method accessed from inside the class and out side

the class• Member method• Non-member method• Main function

Page 31: Object Oriented Programming (OOP)

Variable/method Access Specifer

• Variable– Access_specifier type variable_name;

• private int x;• public int y;• int z; // without specify mean deafult

• Method– Access_specifier return method_name(paramater);

• private int getX();• public int setY(int yy);• int getZ(); // without specify mean deafult

Page 32: Object Oriented Programming (OOP)

Example of default/public AccessPackage www.ssss Package www.ssss Package www.zzzzClass A{ private int x; int y; public int z; public void test(){ x=5; y=3; z=2; }}Which assignment correct?

Class B{ public void test(){ x=5; y=3; z=2; }}

Which assignment correct?

Class C{ public void test(){ x=5; y=3; z=2; }}

Which assignment correct?

Page 33: Object Oriented Programming (OOP)

Method Overloading• Multiple methods share the same method name, but each

of them is with a different parameter set (different method signature)– Examples:

int method()int method(int a)String method(int a, String b)void method(int a, int b)void method(String a, int b)

- Or:System.out.println(…)

Page 34: Object Oriented Programming (OOP)

Constructor Overloading• Like methods, constructors can be overloaded• This offers greater flexibility and convenience of creating objects• Example of Date Constructor

– Date (){D = 12;M= 7;Y= 2009;

}– Date (int day, int month, int year){

D = day;M= month;Y= year;

}– Date (Date a){

D = a.D;M= a.M;Y= a.Y;

}

Page 35: Object Oriented Programming (OOP)

Summary

• Object orientation is more of a way of thinking/modeling, rather than just a programming method

• Organize your classes effectively using packages

• Design overloaded methods and constructors effectively

Page 36: Object Oriented Programming (OOP)

Complex

Page 37: Object Oriented Programming (OOP)

Lecture 5

Inheritance Polymorphism

Override & Extend Access Specifier

Inheritance Example

Page 38: Object Oriented Programming (OOP)

Definition of an “Object”

• An object is a computational entity that:1. Encapsulates some state2. Is able to perform actions, or methods, on this

state3. Communicates with other objects via message

passing

Page 39: Object Oriented Programming (OOP)

Structure of a Class Definitionclass name {

declarations

constructor definition(s)

method definitions}

attributes and symbolic constantshow to create and initialize objects

how to manipulate the state of objectsThese parts of a class can

actually be in any order

Page 40: Object Oriented Programming (OOP)

But there’s more…• Classes can be arranged in a hierarchy• Subclasses inherit attributes and methods

from their parent classes• This allows us to organize classes, and to

avoid rewriting code – new classes extend old classes, with little extra work!

• Allows for large, structured definitions

Page 41: Object Oriented Programming (OOP)

27.2 Superclasses and Subclasses (II)

• Using inheritance– Use keyword extendsclass 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

 

Page 42: Object Oriented Programming (OOP)

Example of Class Inheritance

extends

Shape

Rectangleextends

Objects made from this class, for example, have all the attributes and methods of the classes above them, all the way up the tree

Circle Triangleextends

colorborderWidth

Color getColor( )void setBorderWidth( int m )

int computeArea( )

lengthwidth

int computeArea( )

radius baseheightint computeArea( )

Page 43: Object Oriented Programming (OOP)

Polymorphism• An object has “multiple identities”, based on

its class inheritance tree• It can be used in different ways

Page 44: Object Oriented Programming (OOP)

Polymorphism• An object has “multiple identities”, based on

its class inheritance tree• It can be used in different ways• A Circle is-a Shape is-a Object

toString( )equals( Object obj )getClass( )

Shapeextends

extends

Object

Circle

colorborderWidthColor getColor( )void setBorderWidth( int m )

int computeArea( )

radius

Page 45: Object Oriented Programming (OOP)

Polymorphism• An object has “multiple identities”, based on

its class inheritance tree• It can be used in different ways• A Circle is-a Shape is-a Object

toString( )equals( Object obj )getClass( )

Shapeextends

extends

Object

Circle

colorborderWidthColor getColor( )void setBorderWidth( int m )

int computeArea( )

radius

Shape

Circle

Object

A Circle object really has 3 parts

Page 46: Object Oriented Programming (OOP)

How Objects are CreatedCircle c = new Circle( );

Page 47: Object Oriented Programming (OOP)

How Objects are CreatedCircle c = new Circle( );

c

Shape

Circle

Object

1.

Execution Time

Page 48: Object Oriented Programming (OOP)

48

How Objects are CreatedCircle c = new Circle( );

c

Shape

Circle

Object

c

Shape

Circle

Object

1. 2.

Execution Time

Page 49: Object Oriented Programming (OOP)

49

How Objects are CreatedCircle c = new Circle( );

c

Shape

Circle

Object

c

Shape

Circle

Object

c

Shape

Circle

Object

1. 2. 3.

Execution Time

Page 50: Object Oriented Programming (OOP)

50

Three Common Uses for Polymorphism

1. Using Polymorphism in Arrays2. Using Polymorphism for Method

Arguments3. Using Polymorphism for Method

Return Type

Page 51: Object Oriented Programming (OOP)

51

1) Using Polymorphism in Arrays• We can declare an array to be filled with “Shape”

objects, then put in Rectangles, Circles, or Triangles

extends

toString( )equals( Object obj )getClass( )

Shape

Rectangle

extends

extends

Object

Circle Triangleextends

colorborderWidthColor getColor( )void setBorderWidth( int m )

int computeArea( )

lengthwidth

int computeArea( )

radius baseheightint computeArea( )

Page 52: Object Oriented Programming (OOP)

52

1) Using Polymorphism in Arrays• We can declare an array to be filled with “Shape”

objects, then put in Rectangles, Circles, or Triangles

samples(an arrayof Shapeobjects)

[0] [1] [2]

Page 53: Object Oriented Programming (OOP)

53

1) Using Polymorphism in Arrays• We can declare an array to be filled with “Shape”

objects, then put in Rectangles, Circles, or Triangles

[0] [1] [2]

[2]firstShape

Attributes: length = 17 width = 35Methods: int computeArea( )

secondShapeAttributes: radius = 11 Methods: int computeArea( )

thirdShapeAttributes: base = 15 height = 7Methods: int computeArea( )

samples(an arrayof Shapeobjects)

Page 54: Object Oriented Programming (OOP)

54

1) Using Polymorphism in Arrays• We can declare an array to be filled with “Shape”

objects, then put in Rectangles, Circles, or Triangles

[0] [1] [2]

[2]firstShape

Attributes: length = 17 width = 35Methods: int computeArea( )

secondShapeAttributes: radius = 11 Methods: int computeArea( )

thirdShapeAttributes: base = 15 height = 7Methods: int computeArea( )

RectangleCircle Trianglesamples

(an arrayof Shapeobjects)

Page 55: Object Oriented Programming (OOP)

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

Page 56: Object Oriented Programming (OOP)

56

2) Using Polymorphism for Method Arguments

• We can create a procedure that has Shape as the type of its argument, then use it for objects of type Rectangle, Circle, and Triangle

public int calculatePaint (Shape myFigure) { final int PRICE = 5;

int totalCost = PRICE * myFigure.computeArea( ); return totalCost;}

The actual definition of computeArea( ) is known only at runtime, not compile time – this is “dynamic binding”

Page 57: Object Oriented Programming (OOP)

57

2) Using Polymorphism for Method Arguments

• Polymorphism give us a powerful way of writing code that can handle multiple types of objects, in a unified way

public int calculatePaint (Shape myFigure) { final int PRICE = 5;

int totalCost = PRICE * myFigure.computeArea( ); return totalCost;}

To do this, we need to declare in Shape’s class definition that its subclasses will define the method computeArea( )

Page 58: Object Oriented Programming (OOP)

58

3) Using Polymorphism for Method Return Type

• We can write general code, leaving the type of object to be decided at runtime

public Shape createPicture ( ) { /* Read in choice from user */ System.out.println(“1 for rectangle, ” +

“2 for circle, 3 for triangle:”); SimpleInput sp = new SimpleInput(System.in); int i = sp.readInt( );

if ( i == 1 ) return new Rectangle(17, 35); if ( i == 2 ) return new Circle(11); if ( i == 3 ) return new Triangle(15, 7);}

Page 59: Object Oriented Programming (OOP)

Override & Extend

• Subclass use same method name of super class in Both cases Overloading super class method – same parameter & return type

• Override Super Class method:– By replacing super class method by subclass

method• Extend Super Class method:

– By adding functionality to the super method– Using super keyword

Page 60: Object Oriented Programming (OOP)

Relationship between Superclass Objects and Subclass Objects (II)

• Overriding methods– 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

Page 61: Object Oriented Programming (OOP)

More about field modifiers • 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 62: Object Oriented Programming (OOP)

Protect Access Specifier Super Class Sub Class in other packageClass A{ private int x; int y; public int z; protected k;}

Class B extend A{ public void test(){ x=5; y=3; z=2; k=4; }}

Which assignment correct?

Page 63: Object Oriented Programming (OOP)

27.4 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

– Explicit cast• Convert superclass reference to a subclass reference (downcasting)• Can only be done when superclass reference actually referring to a

subclass object– instanceof operator

• if (p instanceof Circle)• Returns true if the object to which p points "is a" Circle

Page 64: Object Oriented Programming (OOP)

64

Superclass Subclasses Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan,

MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount

Inheritance examples

Page 65: Object Oriented Programming (OOP)

Inheritance Example

• Open NetBeans

Page 66: Object Oriented Programming (OOP)

Lecture 6

Inheritance Polymorphism

Override & Extend Access Specifier

Inheritance Example

Page 67: Object Oriented Programming (OOP)

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 68: Object Oriented Programming (OOP)

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 69: Object Oriented Programming (OOP)

Methods – Declaration• Method 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 70: Object Oriented Programming (OOP)

Methods – Invocation• Method 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 71: Object Oriented Programming (OOP)

Methods – Parameter Values• Parameters 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 past by value, not reference ?

Page 72: Object Oriented Programming (OOP)

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 73: Object Oriented Programming (OOP)

Modifiers of the classes• A 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

Page 74: Object Oriented Programming (OOP)

74

Java

• Java is Object-Oriented from the Ground Up• Java has the elegance that comes from being designed

after other OO languages had been in use for many years• Java has strong type checking• Java handles its own memory allocation• Java’s syntax is “standard” (similar to C and C++)• Java is a good teaching language, but it (or something

close) will also be seen by students in industry