1 Exercise /* A lockbox can be open or closed. If closed, only a valid password will open the box. Once the box is open, the contents can be retrieved.

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
ITEC200 – Week03 Inheritance and Class Hierarchies.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism CS351 – Programming Paradigms.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Programming Languages and Paradigms Object-Oriented Programming.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Java Implementation: Part 3 Software Construction Lecture 8.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
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.
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.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance and Access Control CS 162 (Summer 2009)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
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.
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
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
Inheritance ndex.html ndex.htmland “Java.
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)
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
BY:- TOPS Technologies
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
OOP: Encapsulation &Abstraction
Inheritance and Polymorphism
Object-Oriented Programming
Week 4 Object-Oriented Programming (1): Inheritance
Chapter 9 Inheritance and Polymorphism
Java Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
CIS 199 Final Review.
CIS 110: Introduction to computer programming
Presentation transcript:

1 Exercise /* A lockbox can be open or closed. If closed, only a valid password will open the box. Once the box is open, the contents can be retrieved. */ interface LockBox { boolean openBox(String password); // attempt to open, return true if successful boolean isOpen(); // check if box is open Object getStuff(); // get contents if open, or null if closed void destroy (); // discard contents }  Implement a LockBox.  Implement it again, but this time print a warning if the password is wrong. Only warn the user once for each lock box. /* A volatile lock box self-destructs after 3 invalid password attempts. That is, the contents should be destroyed. The user can also ask how many attempts are left. */  Design the interface, and then implement it.

2 Moral We have encapsulation: –Data & Methods together –Data & Implementation hidden – details don’t matter to user But we still have a lot copy-and-paste –Implementations of lockbox and volatile lock box nearly identical Also cannot change/extend behavior without having the source code, or rewriting from scratch. –Calling Microsoft to add a new method is not an option –Asking for source code is less of an option –we could rewrite is from scratch

3 OO-Programming Again OO-Programming = Encapsulation + Extensibility Encapsulation hides details of class implementation Extensibility: want to modify (extend, change) behavior of classes –Without lots of code duplication –Without involving class implementer –Without even having the class source code

4 Wrappers / Adapters Have a LockBox class, but want VolatileLockBox Make a new class to wrap the old one: public class VBox implements VolatileLockBox { … } Adapter: –Takes object of one type, adapts it to a new type –e.g., BufferedReader same as a Reader, but with a readLine( ) method. All other functions defer to the Reader that was passed to the constructor. Good for certain purposes, but still clumsy: –A lot of drudge work writing “wrapper” methods

5 Inheritance Please read for details  Weiss ch. 4

6 Goal Given class A from your supplier, want to create a new class B that extends A in some way. –Changes behavior of some existing methods –Inherits all the remaining methods –Creates some additional methods, fields, etc. –Implements same interfaces, and maybe some new ones –And can be used wherever A can be used e.g., any code that accepted an A should also accept a B

7 Sub-classes XBox String pass Object c openBox( ) isOpen( ) getStuff( ) VBox String pass Object c isOpen( ) getStuff( ) attempts( ) destroy( ) int left openBox( ) class XBox implements LockBox { private String pass; private Object c; private boolean open; public XBox(Object o, String p) { pass = p; c = o; } public boolean openBox(String guess) { if (open) return true; else return (open = pass.equals(guess)); } public boolean isOpen() { return open; } public Object getStuff() { return open ? c : null; } public void destroy() { c = null; } } boolean open destroy( ) class VBox extends XBox implements VolatileLockBox { ??? }

8 Some Terminology Sub-class VBox: – inherits instance variables pass, c, and open from super- class XBox –inherits instance methods isOpen( ), getStuff( ), and destroy( ) from super-class XBox –has its own instance variable tries and instance method attempts –overrides instance method openBox( ) in super-class XBox Overriding: –must have same signature: return type, name, parameters, static or not –BUT may be less restricted in access: private can become public

9 Writing a Sub-class class VBox extends XBox implements VolatileLockBox { private int left; public VBox(Object o, String p) { pass = p; c = o; left = 3; } public boolean openBox(String guess) { if (left = = 0) { destroy(); return false; } else { boolean good; if (open) good = true; else good = (open = pass.equals(guess)); if (!good) tries--; return good; } public int attempts() { return left; } } class XBox implements LockBox { private String pass; private Object c; private boolean open; public XBox(Object o, String p) { pass = p; c = o; } public boolean openBox(String guess) { if (open) return true; else return (open = pass.equals(guess)); } public boolean isOpen() { return open; } public Object getStuff() { return open ? c : null; } public void destroy() { c = null; } }

10 Super-class Privates Inaccessible Problem: –Fields of super-class (XBox) might be private –But sub-class (VBox) needs to manipulate them… –Same goes for private helper methods in super-class Confused? –Sub-class VBox has the private fields and methods (it inherits them) –But only the code defined in XBox can use them Not a solution: –Make everything public instead

11 One Solution Make everything protected instead private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and its sub-classes default = accessible to classes in same “package”

12 Using Protected class VBox extends XBox implements VolatileLockBox { protected int left; public VBox(Object o, String p) { pass = p; c = o; left = 3; } public boolean openBox(String guess) { if (left = = 0) { destroy(); return false; } else { boolean good; if (open) good = true; else good = (open = pass.equals(guess)); if (!good) tries--; return good; } } public int attempts() { return left; } } class XBox implements LockBox { protected String pass; protected Object c; protected boolean open; public XBox(Object o, String p) { pass = p; c = o; } public boolean openBox(String guess) { if (open) return true; else return (open = pass.equals(guess)); } public boolean isOpen() { return open; } public Object getStuff() { return open ? c : null; } public void destroy() { c = null; } }

13 Critique Use protected instead of private? –Decide: will a sub-class ever need to access directly? –But: Exposes some of the “internal state” to the outside world – e.g., to other programmers, hackers, etc. What if they mess up? What if they are evil? Analogy: Car Mods & User-Serviceable Parts –Car has “public” components – paint color, steering wheel, blinkers, radio, etc. Anyone can access these (by design). –What of the rest? spark plugs ? muffler ? ECC (engine control computer)? shocks? airbags?

14 Another Solution class VBox extends XBox implements VolatileLockBox { private int left; public VBox(Object o, String p) { pass = p; c = o; left = 3; } public boolean openBox(String guess) { if (left = = 0) { destroy(); return false; } else { boolean good; if (open) good = true; else good = (open = pass.equals(guess)); if (!good) tries--; return good; } } public int attempts() { return left; } } class XBox implements LockBox { private String pass; private Object c; private boolean open; public XBox(Object o, String p) { pass = p; c = o; } public boolean openBox(String guess) { if (open) return true; else return (open = pass.equals(guess)); } public boolean isOpen() { return open; } public Object getStuff() { return open ? c : null; } public void destroy() { c = null; } }

15 Keyword super In a sub-class, keyword super gives access to members of the super-class that were not inherited super.m(…) for methods super(…) for constructors class VBox extends XBox implements VolatileLockBox { private int left; public VBox(Object o, String p) { super(o, p); left = 3; } public boolean openBox(String guess) { if (left = = 0) { destroy(); return false; } else { boolean good = super.openBox(guess); if (!good) tries--; return good; } } … } class XBox implements LockBox { private String pass; private Object c; private boolean open; public XBox(Object o, String p) { pass = p; c = o; } public boolean openBox(String guess) { if (open) return true; else return (open = pass.equals(guess)); } … }

16 Keyword super Analogous to keyword this Cannot compose – only allowed access to direct super-class: super.super.m(…); // not allowed Uses static binding: –Compiler binds “super.openBox” in VBox directly to XBox.openBox. No dynamic lookup done at run-time.

17 Inheritance as Sub-types Every VBox instance –“is-a” VolatileLockBox (b/c VBox implements it directly) –“is-a” LockBox (b/c VolatileLockBox is sub-type of LockBox)  “is-a” XBox (b/c VBox extends it directly, and so has all the needed fields, methods, etc.) Type Checking? LockBox b = new VBox(“47”, “pw”); // ? VolatileLockBox v = b; // ? XBox x = b; // ? XBox x2 = new VBox(“47”, “guess-me”); // ?

18 Access Restrictions vs. Overriding XBox x2 = new VBox(“47”, “guess-me”); // OK VBox is a sub-type of XBox So: VBox must do anything an XBox can do –Can VBox.openBox( ) be private or protected? Overriding (again): –Must have same signature: return type, name, parameters, static or not –BUT may be less restricted in access: private in XBox can become public in VBox, but not the reverse. –Compiler enforces this rule.

19 Class Hierarchy If no super-class specified, uses java.lang.Object by default All classes derive (eventually) from Object Object has no parent class (super-class) Object XBox Array VBox Subclass of XBox Superclass of XBox Direct superclass of VBox…….

20 Java Uses Single Inheritance Each class picks ONE direct super-class, or uses the default Object as direct super-class Class hierarchy is a tree Each class can implement many interfaces C++ allows multiple inheritance also: –very complicated in practice –Java’s single inheritance + multiple interfaces get most of the benefits, with far fewer complications

21 Single Inheritance + Multiple Interfaces D E F G I A B C interface C extends A,B{ … } class F extends D implements A{ …..} class E extends D implements A,B{ ….} Interfaces Class hierarchy

22 Details, Details Instance methods are inherited by sub-class –public ones can be overridden by sub-class –dynamic “run-time” lookup is used to find which class’ implementation of the method to use (We don’t call them “dynamic methods” for nothing) –sub-class can still get to old method using super.m( ), but no one else can.

23 Details, Details Static “class” methods are “inherited” by sub-class Or not (depending on who you talk to) They seem like they are inherited: class XBox { public static int id( ) { return 1; } } VBox.id( ); // OK: resolves to XBox.id( ) VBox v = null; v.id( ); // OK: same thing XBox x = v; x.id( ); // OK: same thing But then again: class VBox { public static int id( ) { return 2; } } VBox.id( ); // OK: but now resolves to VBox.id( ) VBox v = null; v.id( ); // OK: now resolves to VBox.id() XBox x = v; x.id(); // OK: still resolves to XBox.id()

24 Inheriting Static Methods? We don’t call them “static” for nothing –Compiler binds all static method calls at compile-time –It will “walk up the class tree” to find the method, but you could do that yourself. –It will allow “x.id()”, but this is just shorthand for “XBox.id()”, regardless of actual type of x. Java calls this “hiding” instead of “overriding”.

25 Constructors Constructors are not inherited; so such thing as “constructor overriding” –But: a sub-class constructor can defer to a super-class constructor using keyword super on first line Object initialization can get tricky in sub-classes

26 Variables Java uses static binding for all variables –even “instance” variables? class A { static String s = "A.s"; String i = “a.i"; } class B extends A { static String s = "B.s"; String i = “b.i"; } class C extends B { static String s = "C.s"; String i = “c.i"; } class Confused { public static void main(String args[]) { System.out.println("class.static"); System.out.println(A.s); System.out.println(B.s); System.out.println(C.s); System.out.println(A.i); System.out.println("class.instance"); System.out.println(B.i); System.out.println(C.i); System.out.println("null.static"); A a = null; B b = null; C c = null; System.out.println(a.s); System.out.println(b.s); System.out.println(c.s); System.out.println("Object-of-type-C.instance"); a = b = c = new C(); System.out.println(a.i); System.out.println(b.i); System.out.println(c.i); }

27 Shadowing Variables static variables: –can’t override –three copies stored: A.s, B.s, C.s –compiler decides which one at compile-time instance variables: –can’t override – instead, we “shadow” super-class vars similar to “hiding” of static methods can use super.field from B or C don’t even have to be the same type! –three copies stored in every object –compiler decides which one at compile-time A i = “a.i” B i = “b.i” C i = “a.i” i = “b.i” i = “c.i”