Implications of Inheritance COMP206, Geoff Holmes and Bernhard Pfahringer.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
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. 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,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
From Theory to Practice 1 OOP Overview Reminder – some OOD principles from previous lessons: –Class Inheritance vs. Object Composition –Program.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
OOP Languages: Java vs C++
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
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[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Chapter 3 Introduction to Collections – Stacks Modified
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Implications of Inheritance COMP204, Bernhard Pfahringer.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Programming Languages and Paradigms Object-Oriented Programming.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
CSSE501 Object-Oriented Development. Some OO Design Principles  Majority principles here come from: Design Principles in Java, Bob Tarr.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
More Implications of Inheritance COMP204, Bernhard Pfahringer.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
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.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Objects and Variables Local variables – Confined to single context: allocated on stack – Primitive types such as int or object references – Must be initialized.
ISBN Object-Oriented Programming Chapter Chapter
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Session 6 Comments on Lab 3 & Implications of Inheritance.
CS 152: Programming Language Paradigms March 19 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
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.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
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,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
C11, Implications of Inheritance
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Chapter 11: More on the Implications of Inheritance
Java Programming Language
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

Implications of Inheritance COMP206, Geoff Holmes and Bernhard Pfahringer

Implications OO language must support polymorphic variables Polymorphic variables: memory requirements unknown at compile-time => allocated on the heap Heap allocation => reference semantics for assignment and parameter parsing Also: equality testing == object identity And: memory management necessary => garbage collection (GC)

The Polymorphic variable Square side describe() Shape x,y describe() Circle radius describe() … Shape form = new Circle(10,10,5); form.describe(); form = new Square(15,20,10); form.describe(); …

Memory Layout Stack-based vs. heap-based Stack-based tied to method entry/exit: Allocate space for all local vars on entry Deallocate on exit Access by numeric offset (activation record) Need to know space requirements at compile-time, not possible for polymorphic variables! Java: all objects allocated on the heap (new operator), local vars point to these objects, pointers have a fixed size Java has no pointers, but internally all object values are represented by pointers.

Factorial example static public int factorial(int n) { int c = n-1; int r; if (c>0) r = n*factorial(c); else r = 1; return r; } 0 n:1 4 r:1 8 c:0 0 n:2 4 r:? 8 c:1 0 n:3 4 r:? 8 c:2 third activation record second activation record first activation record Factorial(3)

Alternative approach (e.g. C++) Different approaches are possible C++: want to use stack (efficiency) Assignment: extra fields are sliced off, E.g. a Square is turned into a Shape, Need to distinguish between virtual/non-virtual methods Need destructors, Pointers/references/values Copy-semantics, …

Assignment: reference semantics Box x = new Box(); x.setValue(7); Box y = x; y.setValue(11); System.out.println(x.getValue()); System.out.println(y.getValue()); … 11 x a box y Simple copy pointer value, i.e. point to same heap-location!

Clones If copy desired, must say so, DIY approach: Box y = new Box(); y.setValue(x.getValue()); If common, package into proper method: public Box copy() { Box b = new Box(); b.setValue(getValue()); return b; }

Clones: Java Class Object provides protected method clone() creating a bitwise copy of the receiver, plus interface Cloneable Programmer must override clone() to public and implement Cloneable: public class Box implements Cloneable { … public Object clone() { Box b = new Box(); b.setValue(getValue()); return b; }} Use: Box y = (Box) x.clone(); // must cast !!!!

Clones: caveats Just a shallow copy, sometimes need deep copies x a box a shape y a box x a box a shape y a box a shape SHALLOW DEEP

Parameter passing as assignment Passing a variable considered similar to assignment, as same value accessible through two different names; pass value, loose some control: static void sneaky (Box b) {b.setValue(11);} … x.setValue(7); sneaky(x); System.out.println(x.getValue()); 11

Equality test: object identity Easy for primitives: 7 == (3+4) ‘a’ == ‘\141’ 2 == 2.0 For objects: == implements object identity, therefore: new Integer(7) != new Integer(3+4) If we really want object equality instead of object identidy: equals method

Equality test: object equality Supplied by class Object, can be overridden: class Circle extends Shape { … public boolean equals(Object arg) { return ((arg instanceof Circle) && (radius == ((Circle) arg).radius)); }} Careful: must be symmetric and transitive Heuristic: use == for numbers and null, equals in all other situations

Equality test: bug example Suppose: class Shape { … public boolean equals(Object arg) { return ((arg instanceof Shape) && (x == ((Shape) arg).x) && (y == ((Shape) arg).y)) ; }} And no equals defined in class Square, then: Square s = new Square(10,10,5); Circle c = new Circle(10,10,5); s.equals(c); // succeeds c.equals(s); // fails

Better solution class Shape { … public boolean equals(Object arg) { return ((arg.getClass() == Shape.class) && (x == ((Shape) arg).x) && (y == ((Shape) arg).y)) ; }} class Circle extends Shape { … public boolean equals(Object arg) { return ((arg.getClass() == Circle.class) && (x == ((Shape) arg).x) && (y == ((Shape) arg).y) && (radius == ((Circle) arg).radius)); }} correct, but no inheritance, code duplication

Garbage collection (GC) Heap-based memory not automatically recovered on method exit (unlike stack) Manual management error-prone (like “free” operator in C++): Forget to free: memory leaks Free multiple times Access freed memory Java compromise: have automatic garbage collection: some runtime cost, but not too bad)

Immutable objects cannot be changed after “construction” how to: do not allow modification by not providing “mutators” (methods that change state) making data fields “private” (always good idea) (most likely) prevent against subclassing useful for “value” types, like Integer, String, and so on; safe to use as keys for HashMaps (see code example for explanation) hashCode “rule”: a.equals(b) == true => a.hashCode() == b.hashCode() [only this direction, different objects can have the same hashCode]

Object construction no explicit constructor: system adds “default constructor”: public A() { super(); } At least one constructor given explicitly: no “default constructor” will be added first line in the constructor can explicitly pass on to constructor of the super-class or same class (if not, system will add “super();”) public A() { super(“info”); /* more code */ } public A() { this(0); /* more code */ }

Construction order Data fields are allocated and initialized to default values (0, null, …) *before any* code blocks or constructors; Then the process is top-down (most general class first to most specific last), each time: Data fields are initialized to their actual values (e.g. 1 in the code example), in order Local code blocks are run, in order The respective constructor is run

Bad Inheritance example import java.util.*; public class InstrumentedArrayList extends ArrayList { // The number of attempted element additions private int addCount = 0; public InstrumentedArrayList() { } public InstrumentedArrayList(Collection c) { super(c); } public InstrumentedArrayList(int initialCapacity) { super(initialCapacity); }

cont. public void add(int index, Object o) { addCount++; super.add(index,o); } public boolean addAll(Collection c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; } public static void main(String[] args) { InstrumentedArrayList s = new InstrumentedArrayList(); s.addAll(Arrays.asList(new String[] {”A",”B",”C"})); System.out.println(s.getAddCount()); }

Better: use Composition import java.util.*; public class InstrumentedList implements List { private final List s; private int addCount = 0; public InstrumentedList(List s) { this.s = s; } public void add(int index, Object o) { addCount++; s.add(index, o); } public boolean addAll(Collection c) { addCount += c.size(); return s.addAll(c); }

Composition, cont. public int getAddCount() { return addCount; } // plus all necessary forwarding methods public void clear() { s.clear(); } public boolean contains(Object o) { return s.contains(o); } public boolean isEmpty() { return s.isEmpty(); } … and so on …

Utilities: Arrays class, Collections lots of useful utilities, have a look at the Javadoc, e.g. Arrays.sort(…) Arrays.binarySearch(..) Arrays.toString(..) Arrays.fill(..) Arrays.hashCode(..) Arrays.equals(..) Arrays.asList(..) Arrays.deepEquals(..), deepToString(..) deepHashCode(..) Collections.shuffle(..)

Utilities: System class again lots of useful utilities, have a look at the Javadoc, e.g. System.arraycopy(..) System.nanoTime() System.identityHashCode(..) System.getenv(..) …