770 likes | 952 Views
Object Oriented Programming (OOP). Mohamed Ezz. Lecture 1. History and Concept. Programming Techniques. Unstructured programming Where all implementation in one function Main(){-------} Procedure programming
E N D
Object Oriented Programming (OOP) Mohamed Ezz
Lecture 1 History and Concept
Programming Techniques • Unstructured programming Where all implementation in one function Main(){-------} • Procedure programming Where repeated part of code separated in a function e.g. factorial function • Modular programming Where 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
Some OOP Concept • State Each object has a state based on values of its attribute • Message Object 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 • Behavior Each object has different behaviors according to environment surrounding it e.g. student in the faculty, can be brother/sister in home
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 Class class Point { //attributes int x, int y; //method to access object attributes void setX(int xx) { x= xx; } intgetX() { return x; } void move(intdx, intdy) { 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 inti, where int is the //class and i is the object Point p1 = new Point(); // e.g. char*c; //c=new char[4] Point p2 = new Point(); p1.setX(1); // point mean belong to object p1.setY(3); p2.setX(4); p2.setY(5); System.out.println(p1); //explain how its work p1.move(2,2); } }
Lecture 3 Variable & Method Definitions Constructor Main method Package
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 initialization ClassNameobjectName; //object declaration objectName = newClassName(); // object creation using a class constructor • Or ClassNameobjectName = newClassName(); • Example Course 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 Example Class Date { int day, month, year; Date (){ day = 13; month= 11; year= 1990; } or Date (int d, int m, int y){ day = d; month= m; year= y; } public static void main (String arg[]){ Date today = new Date(); //or Date 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 import second.section1.*; // first approach Or import second.section1.Point; // second approach import second.section2.Date; //fourth without any import in classes belong to same package public static void main (String arg[]){ Point p1= new Point(); // which class Date d1= new date(); //which class second.section1.Date d2 = new second.section1.Date(); // third approach } Date Point Date Point Date Point Second.section1 Second.section2 Second.section3
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 type Overloading Variable Scope Access Specifier Class 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
Class Variable • What is the different between member(instant) variable & class variable?
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 intgetX(); • public intsetY(intyy); • intgetZ(); // without specify mean deafult
Method Overloading • Multiple methods share the same method name, but each of them is with a different parameter set (different method signature) • Examples: intmethod() intmethod(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
Lecture 5 Inheritance Polymorphism Override & Extend Access Specifier Inheritance Example
Definition of an “Object” • An object is a computational entity that: • Encapsulates some state • Is able to perform actions, or methods, on this state • Communicates with other objects via message passing
Structure of a Class Definition classname{ declarations constructor definition(s) method definitions } attributes and symbolic constants how to create and initialize objects how to manipulate the state of objects These 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
Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron 27.2 Superclasses and Subclasses (II) • 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
Example of Class Inheritance Objects made from this class, for example, have all the attributes and methods of the classes above them, all the way up the tree Shape color borderWidth Color getColor( ) void setBorderWidth( int m ) extends extends extends Rectangle Circle Triangle length width base height radius int computeArea( ) int computeArea( ) int 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
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 Object Shape Circle A Circle object really has 3 parts
How Objects are Created Circle c = new Circle( );
How Objects are Created Circle c = new Circle( ); 1. Object Shape Circle c Execution Time
How Objects are Created Circle c = new Circle( ); 1. 2. Object Object Shape Shape Circle Circle c c Execution Time
How Objects are Created Circle c = new Circle( ); 1. 2. 3. Object Object Object Shape Shape Shape Circle Circle Circle c c c Execution Time
Three Common Uses for Polymorphism • Using Polymorphism in Arrays • Using Polymorphism for Method Arguments • Using Polymorphism for Method Return Type