CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.

Slides:



Advertisements
Similar presentations
Lecture 10: Part 1: OO Issues CS 540 George Mason University.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Introduction to Data Structures, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Object Oriented Programming Concepts.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
1 Inheritance in Java CS 3331 Fall Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Programming Languages and Paradigms Object-Oriented Programming.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Peyman Dodangeh Sharif University of Technology Fall 2013.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance and Access Control CS 162 (Summer 2009)
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
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,
CS 884 (Prasad)Java Classes1 Classes Fields, methods, and constructors Inheritance.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Peyman Dodangeh Sharif University of Technology Spring 2014.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
CS 884 (Prasad)Java Names1 Names Scope and Visibility Access Control Packages.
Overview of C++ Polymorphism
CS 884 (Prasad)Java Types1 Language Specification Semantics of constructs. –Definition and use of name-value bindings: Name Resolution. Soundness : No.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
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.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Design issues for Object-Oriented Languages
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Object Oriented Programming
Overloading and Constructors
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Overview of C++ Polymorphism
Inheritance in Java CS 3331 Fall 2009.
CIS 199 Final Review.
Java Programming Language
Lecture 10 Concepts of Programming Languages
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism

CS 3180 (Prasad)L67Classes2 Class Declaration class Point { int x, y; void move (int dX, int dY) { x += dX; y += dY; } A class defines the structure and the behavior of its instances (objects). An instance of Point has two int fields (that store its state). An instance of Point can be a target of the move method (that can change its state).

CS 3180 (Prasad)L67Classes3 Variable Each class declaration adds a type. n Each variable of class type holds a reference to an object. (Cf. pointer) Variable Declaration : Point p1, p; p1 and p can hold references to Point instances. Object creation : Point p = new Point(); –new allocates storage for an object and the default constructor Point() initializes the Point -object. –int -fields x,y are automatically initialized to 0.

CS 3180 (Prasad)L67Classes4 Assignment : p1 = p; –The object reference is copied. Now the object is accessible through both p1 and p. Initialization : –An instance field of a class type is initialized, by default, to null. However, a local variable in a method declaration is not initialized automatically. Implementation: The formal parameters and the local variables in a method are allocated on run-time stack. The objects are allocated on the heap.

CS 3180 (Prasad)L67Classes5 Accessing fields –p.x Invoking methods –p.move(1,5) this –The keyword this refers to the object the method is called on. void move (int ax, int by) { this.x += ax; this.y += by; }

CS 3180 (Prasad)L67Classes6 Method Overloading void move ( Point p ) { x = p.x; y = p.y; } –The same name can refer to two different methods if the method signatures are different, where the signature is the sequence of types of formal parameters (and result) of the method. –In Java, it is illegal for two methods in a class to have the same signature, even if the return types are different. (Cf. Ada, C++)

CS 3180 (Prasad)L67Classes7 Resolution: “Most Specific” Algorithm Find all “overloaded” methods applicable to a call. If one of them matches exactly for all arguments, invoke that method. Otherwise, eliminate all methods that are less specific (more general) than others. If exactly one method remains, then invoke it. Else, report ambiguity.

CS 3180 (Prasad)L67Classes8 Parameter passing mechanism A primitive type formal parameter is initialized by the value of the actual argument. So a method cannot modify the value of the actual argument. types: int, float, char, etc A class type formal parameter is initialized by the the reference value of the actual argument. So a method cannot modify the reference, but can modify the object accessible through it. types: Point, Object, etc Wrapper classes in Java 1.4 and autoboxing in Java 5 facilitate passing of primitive types by reference. types: Integer, Boolean, Character, etc

CS 3180 (Prasad)L67Classes9 Overloaded Constructors Point ( ) { super(); } –Default constructor (call to parent’s constructor) Point(int a,int b) { this.x = a; this.y = b; } –Overloaded constructor Point( Point p ) { this(p.x, p.y); } –this invokes another constructor A constructor gets invoked after storage is allocated for the object and its fields initialized, by default, but before the new returns.

CS 3180 (Prasad)L67Classes10 Subclass Declaration import java.awt.Color; class ColoredPoint extends Point { Color c = Color.RED; ColoredPoint(Color ic) { super(0, 0); c = ic; } –A subclass extends a class by adding new fields and new methods. –Subclass ColoredPoint inherits fields x, y, and method move from class Point.

CS 3180 (Prasad)L67Classes11 Overloading vs Overriding To override a method m of the parent class, define a method m in the subclass that has identical signature. If the signature of the method m in the subclass is different from that of the method m in the class, then the method m is overloaded in the subclass.

CS 3180 (Prasad)L67Classes12 Method Overriding : Efficiency class Rectangle {... float diagonal() { return Math.sqrt( a*a + b*b ); } class Square extends Rectangle { float diagonal() { return ( * a); }

CS 3180 (Prasad)L67Classes13 Method Overriding : Customization by Reuse class Stack {... } class BoundedStack extends Stack { int bound = 10; void push (int i) { if (top < bound) super.push(i); else System.out.println(“eRrOr”); }

CS 3180 (Prasad)L67Classes14 Method Overriding : Abnormality class Birds {... boolean fly () { return true; } class Penguins extends Birds { boolean fly () { return false; }

CS 3180 (Prasad)L67Classes15 Dynamic Dispatching : Specificity Bird b = new Bird(); Penguin p = new Penguin(); Bird bp = p; b.fly() == true p.fly() == false bp.fly() == false The method run on the object referred to by bp for the message fly() is determined by the run- time type of the object (a penguin), and not by the compile-time type of the variable bp (a bird).

CS 3180 (Prasad)L67Classes16 Bird[] bArray = { new Bird(), new Penguin(), new Bird() }; for (i = 0; i < bArray.length ; i++ ) {... bArray[i].fly();... } Motivation: Enables reuse of existing code libraries to call methods on instances of new subclasses without recompilation. Vendors can distribute classes in binary form and yet let users customize them. Polymorphism and Dynamic Binding

CS 3180 (Prasad)L67Classes17 Binding and Type System

CS 3180 (Prasad)L67Classes18 Dynamic Binding in Java class P { public void f(P p) { System.out.println("f(P) in P. "); } class C extends P { public void f(P p) { System.out.println("f(P) in C. "); } public void f(C cp) { System.out.println("f(C) in C. "); }

CS 3180 (Prasad)L67Classes19 class DynamicBinding { public static void main(String[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); }

CS 3180 (Prasad)L67Classes20 Abbreviated Example class P { public void f(P p){} } class C extends P { public void f(P p){} public void f(C c){} } P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc);

CS 3180 (Prasad)L67Classes21 Compile-time vs Run-time (binding) pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); >=P f(P) {} (coercion) >=P f(P) {} (coercion) >=C f(P) {} >=C f(C) {} P f(P) {} (coercion) C f(P) {} (coercion) C f(P) {} C f(C) {} (Dynamic binding)

CS 3180 (Prasad)L67Classes22 Dynamic Binding in C# class P { public virtual void f(P p) { System.Console.WriteLine("f(P) in P. "); } class C : P { public override void f(P p) { System.Console.WriteLine("f(P) in C. "); } public void f(C cp) { System.Console.WriteLine("f(C) in C. "); }

CS 3180 (Prasad)L67Classes23 class DynamicBinding { public static void Main(string[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); }

CS 3180 (Prasad)L67Classes24 Abbreviated Example class P { public virtual void f(P p){} } class C extends P { public override void f(P p){} public void f(C c){} } P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc);

CS 3180 (Prasad)L67Classes25 Compile-time vs Run-time (binding) pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); >=P f(P) {} (coercion) >=P f(P) {} (coercion) >=C f(P) {} >=C f(C) {} P f(P) {} (coercion) C f(P) {} (coercion) C f(P) {} C f(C) {} (Dynamic binding)

CS 3180 (Prasad)L67Classes26 Static Binding in C# (with new (no virtual)) class P { public void f(P p) { System.Console.WriteLine("f(P) in P. "); } class C : P { public new void f(P p) { System.Console.WriteLine("f(P) in C. "); } public void f(C cp) { System.Console.WriteLine("f(C) in C. "); }

CS 3180 (Prasad)L67Classes27 class Binding { public static void Main(string[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); }

CS 3180 (Prasad)L67Classes28 Abbreviated Example class P { public void f(P p){} } class C extends P { public new void f(P p){} public void f(C c){} } P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc);

CS 3180 (Prasad)L67Classes29 Compile-time (binding) vs Run-time pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); P f(P) {} (coercion) P f(P) {} (coercion) C f(P) {} C f(C) {} P f(P) {} (coercion) C f(P) {} C f(C) {} P f(P) {} (Static binding)

CS 3180 (Prasad)L67Classes30 Inheritance – Overloading C++ vs Java

CS 3180 (Prasad)L67Classes31 class Parent { String method(int i) { return "Parent.method(int)"; } } class Child extends Parent { String method(int i, boolean b) { return "Child.method(int,boolean)"; } } class GrandChild extends Child { String method(int i, boolean b) { return "GrandChild.method(int,boolean)"; } } class Overload { public static void main(String[] args) { Child c = new Child(); GrandChild gc = new GrandChild(); System.out.println(c.method(5,true) + "\t" + c.method(6)); System.out.println(gc.method(1,false)+ "\t" + gc.method(2)); } }

CS 3180 (Prasad)L67Classes32 #include class Parent { public: char* method(int i) { return "Parent.method(int)"; } }; class Child : public Parent { public: char* method(int i, bool b) { return "Child.method(int,boolean)"; } }; class GrandChild : public Child { public: char* method(int i, bool b) { return "GrandChild.method(int,boolean)"; } }; int main() { Child* c = new Child(); GrandChild* gc = new GrandChild(); cout method(5,true) method(6); // ERROR cout method(1,false) method(2); // ERROR }

CS 3180 (Prasad)L67Classes33 class Object is the root of the tree- structured class hierarchy. class Point extends Object {... } Multiple inheritance of classes is prohibited. –There is no consensus about how to resolve name conflicts, automatically. –This can improve performance. super(), in default constructor, is unambiguous. In C++ parlance, all Java methods are virtual.

CS 3180 (Prasad)L67Classes34 final field –primitive type: constant value –reference type: fixed object mutable type : object state changeable e.g., Point immutable type : object state constant e.g., String final instance method – method cannot be over-ridden in a subclass. – method call can be optimized by in-lining. final class –cannot be subclassed. –e.g., String Keyword final

CS 3180 (Prasad)L67Classes35 Abstract Classes Classes must implement all the methods. Abstract classes can implement some methods, leaving the rest to subclasses. Interfaces must specify only the signatures of all the methods. –Interfaces and abstract classes cannot be instantiated (to create objects). –Abstract classes provide a framework by factoring commonality among classes.

CS 3180 (Prasad)L67Classes36 Interface Declaration interface Table { boolean isEmpty(); void insert(int key, Object x); Object lookUp(int key); } –An interface specifies constants and signatures of the (public) methods. –An interface extends super-interfaces. –A class implements interfaces.

CS 3180 (Prasad)L67Classes37 import java.util.Hashtable; class MyTable implements Table { Hashtable v = new Hashtable(); public boolean isEmpty() { return v.isEmpty(); } public void insert(int key, Object x) { v.put(new Integer( key ), x); } public Object lookUp(int key) { return v.get(new Integer( key )); }

CS 3180 (Prasad)L67Classes38 Applications of Interfaces Integrating multiple implementations of an abstract data type Unifying classes that are heterogeneous but that exhibit a common behavior. Enables reuse of “higher-level” code or test code. –Dynamic method lookup. Support for multiple inheritance A class can implement multiple interfaces. Enables code sharing by approximating multiple inheritance of classes. Approximating enumerated types Java 5 supports enumerated types explicitly.

CS 3180 (Prasad)L67Classes39 Odds and ends In Java, the class declaration and the implementation of methods are stored in the same place for ease of maintenance. In Java 1.0, object references point at an intermediate data structure which stores the type information and the current heap address of the actual instance data. In Java 1.1, there are direct pointers to heap (that may be relocated by GC).

CS 3180 (Prasad)L67Classes40 Java does not allow explicit manipulation of pointers. finalize() method is defined to reclaim non- Java resources (such as file handles). It is called by Java runtime system automatically before an object is garbage collected. In C++, pointers can refer to both the heap and the run-time stack.

CS 3180 (Prasad)L67Classes41 class Point { int x, y = 0; Point() { count++ ; } static int count; static { count = 0; } static Point origin = new Point(); } Static Variables and Static Methods

CS 3180 (Prasad)L67Classes42 Each class has a single copy of the static variables. These can be accessed by all instances of a class via methods. Static variables are “encapsulated” global variables that can be accessed by prefixing them with classname. Different instances of a class can communicate through these “shared” variables. Static blocks are used to initialize static variables and are run when a class is loaded. Static methods can refer only to static variables (and not to instance variables).

CS 3180 (Prasad)L67Classes43 Covariant Typing Covariant Return Typing allowed in Java 5

CS 3180 (Prasad)L67Classes44 class A { A m() {};} class B extends A { B m() {}; } class C extends A { C m() {}; } Pro: B x = new B(). m(); Instead of: B x = (B) new B(). m();

CS 3180 (Prasad)L67Classes45 class A { A a; void s(A a) {this.a = a;};} class B extends A { void s(B b) {a = b;}; } class C extends A { void s(C c) {a = c;}; } Pro: B x = new B(); x.s(new B()); Con: A x = new B(); C y = new C(); x.s(new C()); // Exception: Expecting a B found a C