Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming (OOP) Mohamed Ezz. Lecture 1 History and Concept.

Similar presentations


Presentation on theme: "Object Oriented Programming (OOP) Mohamed Ezz. Lecture 1 History and Concept."— Presentation transcript:

1 Object Oriented Programming (OOP) Mohamed Ezz

2 Lecture 1 History and Concept

3 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

4 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

5 Class & Object

6 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

7 Messages

8 Lecture 2 Creating your First Class

9 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

10 Point Class class Point {//attributes int x, int y; //method to access object attributes void 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 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); }

11 Lecture 3 Variable & Method Definitions Constructor Main method Package

12 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

13 Using Objects – Object initialization ClassName objectName; //object declaration objectName = new ClassName(); // object creation using a class constructor – Or ClassName objectName = new ClassName(); – Example Course cis3270=new Course(); Course cis2010=new Course();

14 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

15 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); }

16 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.

17 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

18 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); }

19 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)

20 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

21 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.*;

22 Package Date Point Date Point Date Point Second.section1Second.section2Second.section3 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 }

23 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

24 Lecture 4 Reference Data type Overloading Variable Scope Access Specifier Class Variable Complex Class

25 Reference Data Type Reference data type stores memory address (reference) as its value

26 Object Assignment Objects are assigned by reference

27 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

28 Variable Scope

29 Class Variable What is the different between member(instant) variable & class variable? Instant VariableClass Variable DeclarationInside class int x, int y; Inside class with static keyword int static point_count; AccessUsing object p1.x; Using object or Class p1. point_count; Point. point_count; Change ValueEffected in each object Effected for all class Initialized in the class Memory allocation Separate location for each object Shared location for all class objects & the class

30 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

31 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

32 Example of default/public Access Package www.ssss Package www.zzzzwww.zzzz Class 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?

33 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(…)

34 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; }

35 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

36 Complex

37 Lecture 5 Inheritance Polymorphism Override & Extend Access Specifier Inheritance Example

38 Definition of an “Object” An object is a computational entity that: 1.Encapsulates some state 2.Is able to perform actions, or methods, on this state 3.Communicates with other objects via message passing

39 Structure of a Class Definition class name { 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

40 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

41 27.2Superclasses 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 Shape TwoDimensionalShape ThreeDimensionalShape CircleSquareTriangleSphereCubeTetrahedron

42 Example of Class Inheritance extends Shape Rectangle extends 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 Triangle extends color borderWidth Color getColor( ) void setBorderWidth( int m ) int computeArea( ) length width int computeArea( ) radius base height int computeArea( )

43 Polymorphism An object has “multiple identities”, based on its class inheritance tree It can be used in different ways

44 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

45 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 Shape Circle Object A Circle object really has 3 parts

46 How Objects are Created Circle c = new Circle( );

47 How Objects are Created Circle c = new Circle( ); c Shape Circle Object 1.1. Execution Time

48 48 How Objects are Created Circle c = new Circle( ); c Shape Circle Object c Shape Circle Object 1.1. 2.2. Execution Time

49 49 How Objects are Created Circle c = new Circle( ); c Shape Circle Object c Shape Circle Object c Shape Circle Object 1.1. 2.2. 3.3. Execution Time

50 50 Three Common Uses for Polymorphism 1.Using Polymorphism in Arrays 2.Using Polymorphism for Method Arguments 3.Using Polymorphism for Method Return Type

51 51 1) Using Polymorphism in Arrays We can declare an array to be filled with “Shape” objects, then put in Rectangles, Circles, or Triangles

52 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 array of Shape objects) [0][1][2]

53 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] firstShape Attributes: length = 17 width = 35 Methods: int computeArea( ) secondShape Attributes: radius = 11 Methods: int computeArea( ) thirdShape Attributes: base = 15 height = 7 Methods: int computeArea( ) samples (an array of Shape objects)

54 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] firstShape Attributes: length = 17 width = 35 Methods: int computeArea( ) secondShape Attributes: radius = 11 Methods: int computeArea( ) thirdShape Attributes: base = 15 height = 7 Methods: int computeArea( ) Rectangle Circle Triangle samples (an array of Shape objects)

55 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 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 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 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); }

59 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

60 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

61 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

62 Protect Access Specifier Super ClassSub Class in other package Class 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?

63 27.4Relationship 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 64 Inheritance examples

65 Inheritance Example Open NetBeans

66 Lecture 6 Inheritance Polymorphism Override & Extend Access Specifier Inheritance Example

67 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 follows System.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

68 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

69 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

70 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

71 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 ?

72 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 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 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”!

73 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 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


Download ppt "Object Oriented Programming (OOP) Mohamed Ezz. Lecture 1 History and Concept."

Similar presentations


Ads by Google