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

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Lecture 2: Object Oriented Programming I
Object Oriented Programming. Problem Description “ …customers are allowed to have different types of bank accounts, deposit money, withdraw money and.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
C++ fundamentals.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Programming in Java CSCI-2220 Object Oriented Programming.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Final and Abstract Classes
Presentation transcript:

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

Class & Object

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

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

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 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();

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 – 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 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 }

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

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 Access Package Package 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?

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 state 2.Is able to perform actions, or methods, on this state 3.Communicates with other objects via message passing

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

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

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

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

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

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

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

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

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 1) Using Polymorphism in Arrays We can declare an array to be filled with “Shape” objects, then put in Rectangles, Circles, or Triangles

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

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

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

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

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