Upload
vincent-barton
View
224
Download
0
Embed Size (px)
Citation preview
Object Oriented Programming (OOP)
Mohamed Ezz
Lecture 1
History and Concept
Programming Techniques
• Unstructured programmingWhere 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
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
Class & Object
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
Messages
Lecture 2
Creating your First Class
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
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);
}}
Lecture 3
Variable & Method DefinitionsConstructor
Main methodPackage
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
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();
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
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);}
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.
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
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);
}
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)
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
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.*;
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}
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
Lecture 4
Reference Data typeOverloading
Variable ScopeAccess SpecifierClass Variable Complex Class
Reference Data Type
• Reference Data Type• Reference data type stores memory address
(reference) as its value
Object Assignment
• Objects are assigned by reference
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
Variable Scope
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
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
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
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?
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(…)
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;
}
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
Complex
Lecture 5
Inheritance Polymorphism
Override & Extend Access Specifier
Inheritance Example
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
Structure of a Class Definitionclass name {
declarations
constructor definition(s)
method definitions
}
attributes and symbolic constants
how to create and initialize objects
how to manipulate the state of objectsThese parts of a class can
actually be in any order
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
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
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( )
Polymorphism• An object has “multiple identities”, based on
its class inheritance tree• It can be used in different ways
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
colorborderWidth
Color getColor( )void setBorderWidth( int m )
int computeArea( )
radius
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
colorborderWidth
Color getColor( )void setBorderWidth( int m )
int computeArea( )
radius
Shape
Circle
Object
A Circle object really has 3 parts
How Objects are CreatedCircle c = new Circle( );
How Objects are CreatedCircle c = new Circle( );
c
Shape
Circle
Object
1.1.
Execution Time
48
How Objects are CreatedCircle c = new Circle( );
c
Shape
Circle
Object
c
Shape
Circle
Object
1.1. 2.2.
Execution Time
49
How Objects are CreatedCircle c = new Circle( );
c
Shape
Circle
Object
c
Shape
Circle
Object
c
Shape
Circle
Object
1.1. 2.2. 3.3.
Execution Time
50
Three Common Uses for Polymorphism
1. Using Polymorphism in Arrays2. Using Polymorphism for Method
Arguments3. Using Polymorphism for Method
Return Type
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
colorborderWidth
Color getColor( )void setBorderWidth( int m )
int computeArea( )
lengthwidth
int computeArea( )
radius baseheight
int computeArea( )
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]
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]
firstShapeAttributes: length = 17 width = 35Methods: int computeArea( )
secondShapeAttributes: radius = 11 Methods: int computeArea( )
thirdShapeAttributes: base = 15 height = 7Methods: int computeArea( )
samples(an arrayof Shapeobjects)
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]
firstShapeAttributes: length = 17 width = 35Methods: int computeArea( )
secondShapeAttributes: radius = 11 Methods: int computeArea( )
thirdShapeAttributes: base = 15 height = 7Methods: int computeArea( )
RectangleCircle Trianglesamples
(an arrayof Shapeobjects)
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
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”
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( )
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);}
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
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
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
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?
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
64
Superclass Subclasses
Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan,
MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount
Inheritance examples
Inheritance Example
• Open NetBeans
Lecture 6
Inheritance Polymorphism
Override & Extend Access Specifier
Inheritance Example
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
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
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
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
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 ?
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”!
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
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