1 Object Oriented Programming OOP: Many things to many people Some common elements –Objects = state + behavior –Interfaces –Classes –Subtyping, polymorphism.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
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.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Chapter 10 Classes Continued
OOP Week 4 1 Object Oriented Programming in Java Monday, Week 4 Last week’s asst. –rating…. This week’s asst. OOP Concepts Inheritance & Substitutability.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
OOP Languages: Java vs C++
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Introduction to Object Oriented Programming CMSC 331.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance and Access Control CS 162 (Summer 2009)
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Object-Oriented Programming Chapter Chapter
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
3C-1 Purity Typing Language semantics Inheritance model  Single vs. Multiple inheritance  Common root Modular mechanisms Generics Object Oriented Languages.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
ISBN Chapter 12 Support for Object-Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Design issues for Object-Oriented Languages
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Inheritance Inheritance is a fundamental Object Oriented concept
Java Programming Language
Lecture 10 Concepts of Programming Languages
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

1 Object Oriented Programming OOP: Many things to many people Some common elements –Objects = state + behavior –Interfaces –Classes –Subtyping, polymorphism –Inheritance and overriding We’ll look at these in the context of Java

2 The Java Programming Language TM C-like syntax Safe execution model –Static type checking –No uninitialized variables –A few dynamic checks –Array bounds checking –No pointer arithmetic –No dangerous type casts “Mostly Object Oriented”

3 Objects A chunk of state (i.e. variables, a.k.a. fields) with some behavior (i.e. operations, a.k.a. methods) int x, y; void set_pos(int newx, int newy) { x = newx; y = newy; } void move_up() { set_pos(x, y + 20); } Structure a program as a collection of objects –E.g. data structures, files, GUI widgets, devices –…, numbers, algorithms, … everything!

4 Features of Java Objects State (often hidden) Methods operating on and revealing state Dynamic dispatch –Method implementation selected at runtime Reference semantics –Different variables may refer to the same object Types describing how objects may be used

5 Hiding State Improve modularity by hiding information [Parnas] int x, y; void set_pos(int newx, int newy) { x = newx; y = newy; } void move_up() { set_pos(x, y + 20); } x and y are not accessible outside the object We can change the object’s implementation without affecting users of the object –E.g. int x, y --> int coords[2]

6 Hiding State in Java Keywords: public, private private int x, y; public void set_pos(int newx, int newy) { x = newx; y = newy; } public void move_up() { set_pos(x, y + 20); } Public variables and/or private methods are also allowed

7 Interfaces The parts of an object accessible from outside public void set_pos(int newx, int newy); public void move_up(); Objects come with a formal or informal specification that defines what the interface does

8 Method Invocation We need to specify which object is used when we call a method p1.set_pos(100, 0); p1.move_up(); p2.set_pos(100, 20); We look up p1 and p2 at runtime to see which implementations of set_pos and move_up to use –“Dynamic dispatch”/“late binding”/“virtual call” –The same line of code can get different implementations for different values of p1

9 Object References p1 and p2 are object references “p1 = p2” has reference semantics –p1 and p2 end up referring to the same object An object reference always refers to a valid object (references cannot be forged) –Except “null” references are allowed (unfortunately) –Every object reference either refers to a valid object or is null (like ‘option’ in ML)

10 Object Equality Reference equality tests if two references are the same object –“p1 == p2” “Deep” equality tests if two objects represent the same thing –“p1.equals(p2)” E.g. p1 and p2 both represent (100, 20), p1.equals(p2) but p1 != p2

11 Classes Need families of objects with the same methods but with different internal state Java solution: group objects into classes class Point { private int x, y; public void set_pos(int newx, int newy) {…} public void move_up() {…} }

12 Features of Java Classes All objects of a given class have the same methods Create new objects of a given class (“new Point()”) Use inheritance to share code between classes Classes define boundaries for hiding information Per-class code and data (“static”) A class defines a type and a tag for objects

13 Creating Objects Create an object with “new classname” Automatically calls a constructor method –Helpful for establishing object invariants class Point { private int x, y; public Point(int initx, int inity) { x = initx; y = inity; } … } Point p = new Point(100, 100);

14 Inheritance Can declare one class to be a subclass of another –Each method (and field) in the superclass can be inherited by the subclass class ColoredPoint extends Point { public void set_color(Color color) {…} } ColoredPoint gets methods set_pos and move_up from Point This is just a way to reuse code

15 Overriding Superclass methods can be overridden class ColoredPoint extends Point { public void set_pos(int newx, int newy) { x = newx; y = newy; set_color(BLACK); } public void set_color(Color color) {…} } ColoredPoint only gets method move_up from Point This allows specialization of reused code

16 Fun With Inheritance/Overriding This invokes Point.move_up on p –By default, methods operate on “this” (current obj.) –Which set_pos is called? –ColoredPoint.set_pos !!! –Because even though we’re in the code for a Point, methods are always selected according to the dynamic (run-time) class of the object ColoredPoint p = new ColoredPoint(); p.move_up();

17 Fun With Inheritance/Overriding class Point { private int x, y; public void set_pos(int newx, int newy) { x = newx; y = newy; } public void move_up() { set_pos(x, y + 20); } } class ColoredPoint extends Point { public void set_pos(int newx, int newy) { x = newx; y = newy; set_color(BLACK); } public void set_color(Color color) {…} }

18 Class Hierarchy The graph of subclass relationships Object StringNumber Every class has a superclass, except for the root class “Object” IntegerFloat

19 Controlling Subclassing/Overriding A Java class can be declared “final” –No subclass can be created final class ColoredPoint extends Point { … } A Java method can be declared “final” –It cannot be overriden in a subclass class ColoredPoint extends Point { final public void set_color(Color color) {…} } Can improve efficiency, and guide reuse

20 Multiple Inheritance Can cause problems with ambiguities –What if Colorable defines a set_pos method? Java allows at most one superclass –(This code is not legal) class Colorable { public void set_color(Color color) {…} } class ColoredPoint extends Point, Colorable {}

21 Access Control We’ve seen “public” and “private” –“private”: field or method only accessible by code in the same class “protected” –Field or method only accessible by code in the same class or a subclass In Java, classes can be grouped into packages, which also affect access control

22 Static Methods and Fields Every method or field belongs to some class Sometimes we want methods or fields that belong to no particular object (global variables, functions) –“static” methods and fields class Math { static double PI = ; static double pow(double x, double n) {…} … }

23 Base Types in Java Not everything is an object (unlike, e.g. Smalltalk) –Primitive numeric types: byte, short, int, long, char, float, double –Primitive boolean type Makes implementation easier, and more like C/C++, but the language is less uniform Standard “wrapper classes” exist to package primitive values inside objects –e.g. “new Integer(42);”

24 Types What is the type of an object reference? p.set_pos(100, 100); To check whether this is valid, the type of p must specify which methods are available We could have types like this: [public void set_pos(int newx, int newy), public void move_up()] But these get large and nasty

25 Class Types Let the type of an object reference be the name of a class Point p; p.set_pos(100, 100); Check call by examining the methods in class Point Makes it easy to write type declarations static void move_up_twice(Point p) { p.move_up(); p.move_up(); }

26 Structural Subtyping Can we pass a ColoredPoint to move_up_twice? –Each method of Point is supported by ColoredPoint –Therefore, as far as one can tell by looking at interfaces, “every ColoredPoint is also a Point” –We could say ColoredPoint is a subtype of Point –A form of polymorphism: move_up_twice can be applied to different kinds of objects class ColoredPoint { public void set_pos(int newx, int newy) {…} public void move_up() {…} public void set_color(Color color) {…} }

27 Behavioral Subtyping Make Cowboy a subtype of Graphic only if Cowboy satisfies the specification of Graphic [Wing] But we can’t check this automatically class Graphic { public void draw() {…} } class Cowboy { public void draw() {…} public void shoot() {…} }

28 Subtyping in Java class ColoredPoint extends Point { public void set_pos(int newx, int newy) {…} public void move_up() {…} public void set_color(Color color) {…} } Subtype relationships declared explicitly by subclassing Simple, but not very flexible –Sometimes we want subtype relationships that the original programmer didn’t think of

29 Inheritance vs Subtyping In Java, subclassing controls both subtyping and inheritance These really should be separated –Sometimes we want to reuse code without creating a subtype relationship –Sometimes we want a subtype relationship without reusing code

30 Arrays in Java All arrays created dynamically –Size specified at runtime –Bounds checking at runtime Arrays are special subclasses of Object –In particular, arrays are accessed by reference int[] numbers = new int[100]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i; } System.out.println(numbers[50]);

31 Arrays and Subtyping In Java: A subtype of B  A[] is a subtype of B[] –This allows some useful code to be written static void printAll(Object[] things) { for (int i = 0; i < things.length; i++) { System.out.println(things[i].toString()); } } ColoredPoint[] coloredPoints = …; printAll(coloredPoints);

32 Java Arrays are Broken To prevent this, every store into an array of objects incurs a runtime check --- YUCK A[] should never be a subtype of B[] (unless A=B) static void evilPrintAll(Object[] things) { … things[0] = new Point(); // typechecks! } ColoredPoint[] coloredPoints = …; evilPrintAll(coloredPoints); coloredPoints[0].set_color(BLACK); // BOOM

33 Java Interface Classes Java “interface”: a special kind of class –Contains no fields or method implementations –Contains only a list of methods that must be implemented by subclasses interface Colorable { public void set_color(Color color); } class ColoredPoint extends Point implements Colorable { public void set_color(Color color) {…} }

34 Interface Classes Java allows multiple inheritance of interfaces –No ambiguity about which method body to inherit –Since each interface declares a type, we can now have types that are subtypes of more than one type interface Colorable { public void set_color(Color color); } interface Positionable { public void set_pos(int newx, int newy); } class ColoredPoint extends Point implements Colorable, Positionable {…}

35 Limitations of Java’s Type System Consider a general stack class class Stack { … public void push(Object obj) {…} public Object pop() {…} } Stack s = new Stack(); s.push(new Point()); Point p = s.pop(); // Doesn’t typecheck There’s no way to parameterize Stack with the type of objects that it will contain

36 Downcasting Solution: add a “downcast” declaring that the popped Object is really a Point –Runtime checks ensure that it is really a Point Stack s = new Stack(); s.push(new Point()); Point p = (Point)s.pop(); Slow, can lead to unfortunate runtime errors –Even the best languages seem to need it sometimes Also have instanceof: “if (p instanceof Point) …”

37 Tagging (“Runtime Types”) “instanceof” and downcasting require every object to retain a class tag at runtime Each class has a unique tag Tag sometimes referred to as “dynamic type” of the object Tags accessible to the programmer via “obj.getClass()” (reflection)

38 Frameworks Library design: Reuse code by inheriting and specializing framework base classes –Often used for GUIs (e.g. AWT, Swing, MFC) –“Given generic app, specialize it to what you want” ContainerContainee WindowButtonGraphics AppWinAppButton Application UI Lib Container Lib

39 Frameworks Advantages over other approaches (e.g. “layered libraries”) –Get started quickly (prototyping) –Can hide control flow in the framework –May allow more flexible customization Disadvantages –Dynamic dispatch can lead to spaghetti code –Interface between (e.g.) AppWin and Window code is complex, hard to specify, and fragile