Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
Lecture 5: Interfaces.
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.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
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.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
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.
Lesson 3 Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example:
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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.
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,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
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.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
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.
Object Oriented Software Development
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
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
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
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
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
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.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Packages and Interfaces
Final and Abstract Classes
Presentation transcript:

Interfaces, Inhteritance, Polymorphism

What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface FooInterface{ void foo1(); int foo2(double x); } abstract interface FooInterface{ public abstract void foo1(); public abstract int foo2(double x); } Both are correct! the abstract and public keywords are implied, so the shorthand is recommended.

Interfaces, cont.  Unlike a class, an interface cannot be instantiated!  Rather, an interface is implemented by some other class: class FooClass implements FooInterface{.... }  This means one thing only: FooClass must contain versions of both foo1 and foo2 that actually do something useful. We say that FooClass must provide implementations for all of the methods in FooInterface.

Interfaces, cont.  When a class implements an interface, think of the class as entering a contract to provide meat for all methods in the interface.  The compiler will check that this contract is adhered to.  Otherwise, the class implementing the interface can contain anything else that a regular class contains.  Again: do not try to instantiate an interface – this is meaningless!

More interface rules  A class may implement any number of interfaces as: class FooClass implements A, B, C{... }  An interface may also contain public static final variables. Usually, these qualifiers are left off. We just say: interface MyConstants{ double PI = ; double E = ; } can be acessed as either MyConstants.PI or just PI by any class that implements the interface

Certification-type questions  What happens when multiple interface implementation results in name conflicts? –if the methods have different signatures, they are considered overloaded and there is no problem –if the methods have the same signature and the same return type, they are considered to be the same method. –if they have the same signature and different return types, a compilation error will result. –If they have same signature/return type but throw different exceptions, they are considered to be same, and resulting throws list is union of original two

Marker Interfaces  Some interfaces contain no methods or constants at all (ie they are empty).  These are called “marker interfaces”.  Examples are Cloneable and Serializable in java library.  We will understand these better once we understand subtype-supertype relationships.

Subtyping with Interfaces  Understanding mechanics of interfaces is only about 1/3 of the story.  Next, we have to understand how interfaces allow for polymorphism.  Finally, we study probably the hardest part – how to best use polymorphism to really write superior code.

Rules of subtyping  If class C implements interface I, then C is a subtype of I.  What does this imply? We can do things like: C aC; aC = new C(); I aC; aC = new C();  In the latter case, we often say that the runtime type of aC is C, but the static or declared type is I.  In the former case, both types are C This is the regular stuff Can do this also!

Substitutability of Types  Rule: A value of a subtype can appear wherever a value of its supertype is expected. In other words, a value of a sybtype can always substitute for a value of a supertype.  To rephrase for objects: An instance of a subclass can appear wherever an instance of a superclass is expected. Note: superclass here refers to interface at this point. We will make more general soon.

Generic examples of subtyping class Circle implements Drawable, Scalable{... Circle aCircle; Drawable aDrawable; Scalable aScalable; aCircle = new Circle(); //ok aCircle = new Drawable(); //BAD! aDrawable = new Circle();//ok aScalable = new Circle(); //ok 1,3,4 are ok because a Circle object is created and it is assigned to a declared type of either Circle or one of its supertypes.

More examples Drawable aDrawable; Circle aCircle; aCircle = new Circle();//fine aDrawable = aCircle;//fine – aDrawable is type superclass aDrawable = new Circle(); aCircle = aDrawable; //NO; cannot assign more general to //more specific without an explicit //cast aCircle = (Circle) aDrawable; //this is ok – explicit cast!

Widening and Narrowing  The conversion of a subtype to one of its supertypes is called widening. The conversioning of a supertype to one of its subtypes is called narrowing.  Widening happens automatically during an assignment. Nothing special is required. This is also typically called upcasting.  Narrowing requires a proper explicit cast, otherwise the compiler will complain. This is an example of Java’s very strong typing. It is your best friend. Narrowing is also known as “downcasting”.

ClassCasts and instanceof  The java compiler will allow any cast. If the cast is illegal, a runtime exception will be thrown (ClassCastException).  There are two ways to safeguard against this. 1.with a try-catch block (later) 2.Using the instanceof operator as: if (aDrawable instanceof Circle){ aCircle = (Circle) aDrawable } instanceof tells the actual type of an object rather than its declared type.

Why on earth do this?  How could this ever be used to your advantage? Why not simlply type all Circles as Circle, etc. In other words, why ever do: Drawable aCircle = new Circle(); vs. Circle aCircle = new Circle();  Much easier to understand if we use upcasting in method calls.

Using Upcasting in method calls Imagine there is a class Renderer that has a method Render that can operate on any object that knows how to morph any two objects that can draw themselves. e.g.; class Renderer{... public void morph(Drawable o1, Drawable o2){ // calls made to o1.draw(), o2.draw() here\ } You can call morph as e.g.: Renderer rn = new Renderer(); Circle c = new Circle(); Rectangle r = new Rectangle(); rn.morph(c,r); //c,r are automatically upcast to Drawables

Comparable interface  Another good example is Java’s Comparable interface, which contains the compareTo method.  One of the Arrays.sort methods operates on any array of Objects that implement the Comparable interface.  Thus, specific objects to be sorted are implicitly upcast when passed to the sort method.

When is downcasting needed?  Once an object is upcast, you cannot call methods that do not exist in the supertype.  For example, if Rectangle objects have a method called rotate(), that method cannot be called from within morph unless an explicit downcast is performed.  This is an example of Java’s strong typing. The compiler cannot be sure that the actual object passed in has a rotate method, so it forces you to say so explicitly.

Extending interfaces  An interface may also extend another interface.  In that case, the extender is known as the superinterface and the extendee is the subinterface.  Example: interface FooInterface{ int foo1(); } interface FooInterface2 extends FooInterface{ int foo2(); } FooInerface2 contains both methods foo1 and foo2, and anything that implements FooInterface2 must implement both of these.

Part III: How interfaces are used  This is difficult because there is no single, simple answer to the question.  Like any semantic feature in a programming language, there are no hard and fast rules about in what situations it should best be exploited.  However, there are many guidelines and general strategies (or else the feature would have never bee included).  We’ll cover a few ways in which interfaces are typically used.

Some interface uses 1. To simply clarify the the functionality associated with a particular abstraction. 2. To abstract functionality in a method to make it more general, such as pointers to functions are used in C. sort is a good example. 3. To implement callbacks, such as in GUI programming 4. To write more general, implementation depending code that is easy to extend and maintain. 5. To simulate global constants.

Clarifying functionality  Often you just want to write a code to do something. It will never do anything else. You are not concerned about extensibility.  Even in such a case, it can be nice to organize your program using interfaces. It makes the code easy to read and the intent of the author very clear.

Callbacks  Callbacks are a general programming technique where a method call another method which then calls the calling method (typically to inform the caller when some action has taken place).  Timer and Swing ActionListeners are good examples.

To write more general implementation  A method that operates on a variable of type interface automatically works for any sub- type of that interface.  This is much more general than writing your program to operate only on a particular subtype.  See Shape example.

Abstracting functionality  A method can often be made more general by customizing its work based on the implementation of some other function that it calls.  sort(...) is a good example. A sort() function can sort any list of items as long as you tell it how to compare any two items.  Numerical methods for solvering differential equations often depend on taking discrete derivatives: you can make such a routine general by specifying the derivate technique independently.

Ineritance

Basic inheritance  Interfaces can be thought of as a special case of a more general class relationship called inheritance.  When a class C2 inherits from or extends another class C1, C1 is called the superclass of C2, and C2 the subclass of C1.  This means that all of the public and protected members of the superclass are available to the subclass. This includes implementation and instance variables!  Any class that is not explicitly declared as final can be extended.

Inheritance syntax For one class to be a subclass of another, we use the extends keyword: class GradStudent extends Student{...} class Manager extends Employee{...} etc. The superclass requires no special syntax.

Subtyping  Everything we learned about typing and subtyping holds a fortiori for super and subclasses.  Specifically, classes which extend other classes are of both type superclass and type subclass.  A class can only extend a single class (no multiple implementation inheritance).

Method overriding  Overriding refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method in the superclass.  Implementation of this method in the subclass replaced the implementation of the method in the superclass.

Overriding example class A{ public void m1(){...} } class B extends A{ public void m1(){...} } For objects of class B, its own unique version of m1 will be called. We say that the method m1 in B overrides the method m1 in its superclass.

What is the point?  Great advantage of implementation inheritance is code re-use.  By factoring functionality common among many classes to a single superclass, each subclass is much simpler.  Furthermore, code changes need to occur in only one place.  However, when distributing a library, this can also be anathema to clients when used non- judiciously – breaks encapsulation!

When to use inheritance  As with every semantic construct, there are no firm rules. Even general guidelines are not uniformly agreed upon.  A non-controversial statement is probably: Be very careful not to overuse. Deep inheritance hierarchies are very hard to keep track of and maintain.  We will be exploring these issues constantly throughout the rest of the class.

The rules: Certification fodder  The easier (but still sometimes subtle) question is what the exact rules are.  Divide rules up into several sections –instance variables –constrcutors –methods –issues with static iv’s and methods

Rules for instance variables  First must understand concept of a package in Java.  A package is a collection of related class definition. For example, java.lang, java.util, java.util.regex, etc.  Classes that are not placed within a package are automatically in the “default package”.  It’s generally a good idea to explicitily place all of your programs within a package.

Using classes from a package  Two ways to access classes from a package: –use full package name: java.util.ArrayList x = new java.util.ArrayList(); –use import statement: import java.util.ArrayList then can use just class name everywhere after import  What if names conflict? –compiler warning –must use full name to distinguish  Can also use wildcard for all classes in package –import javva.util.*;

Creating packages  To create a package, place the package identifier at the top of your source code. e.g. package myjava.lib;  This places the current class/classes in a package called myjava.lib (notice the lowercase convention for package names).  Important: this class must be placed in a corresponding directory structure $ROOT/myjava/lib.  Your CLASSPATH must contain $ROOT

Class visibility  Classes themselves can be public or default (I’m avoiding discussion of inner classes here) public class Foo{...} class Foo{... }  classes that are public are visible outside of their package  classes that are default are visible only within their package  Every source code file can have at most one public class but infinitely many package-scope classes.

Rules for instance variables  public: accessible from any class  default: accessible from any class within same package  protected: default + any subclass  private: accessible only in class where defined. –note: this includes any object created from that class

More on private iv’s  If class B extends class A and A has private iv’s, those iv’s are part of class B.  However, those iv’s cannot directly be accessed by class B.  This is an important distinction – they are part of class B, but cannot be accessed directly by class B!?  class B would have to call non-private accessor/mutator methods to access A’s iv’s.

Private vs. Protected iv’s  To give direct access to superclass iv’s, make them protected.  This is sometimes a very good idea, and sometimes a very bad idea. Ideas?  Horstmann points out that it breaks encapsultion. This is true, but the whole idea of inheritance breaks encapsulation.  General rule: when constructing a library, be very careful when making anything non-private, espcially iv’s. When programming within a package, requirements less stringent.

Rules for constructors  Unlike other methods and iv’s, constructors are not inherited  When instantiating a class B that is a subclass of some class A: –To call A’s constructor the first line of B’s constructor must be super(...); // assume this is a valid constructor –super(...) may be ommitted if you wish to call the superclass default constructor.

Rules for methods  Visibility rules are the same for variables.  Public methods are often preferred way to access iv’s.  A method in a superclass may be redefined in a subclass. This is called overriding (see next slide).  Regular rules of overloading apply.

Method overriding  Overriding refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method in the superclass.  Implementation of this method in the subclass replaced the implementation of the method in the superclass.

Simple examples Best to start abstract. Let’s do data-only classes: class A{ private int iv1; public int iv2; protected int iv3; int iv4; } class B extends A{

Overriding example class A{ public void m1(){...} } class B extends A{ public void m1(){...} } For objects of class B, its own unique version of m1 will be called. We say that the method m1 in B overrides the method m1 in its superclass.

Rules for static methods and fields  Static methods and fields cannot be overriden.  I don’t ever do this. Please consult book if you are interested. It is not typical.

Abstract classes  We’ve covered two extremes of inheritance: –interfaces: all methods are abstract in superclass and superclass (ie interface) serves to define common type –non-abstract superclasses: all methods are non- abstract in superclass and subclass actually inheritents implementation. good for code re-use also good for defining common type

Abstract classes, cont.  Using abstract methods, we can actually program in between these two models.  This is done by creating superclasses that are mixtures of abstract and non-abstract methods plus iv’s.  The non-abstract methods and iv’s are inherited just like with regular classes.  The abstract methods are treated just like interface methods – they must be implemented.

Rules for abstract classes  Any method in a class may be given the abstract keyword. public abstract void foo(...)  If one or more methods in a class are abstract, the class itself must be declared abstract abstract class Foo{...}  Abstract classes may be subclassed, but not instantiated.

More on abstract classes  Abstract methods must have no meat.  It is not required that a subclass implement every (or any) abstract method in an abstract superclass.  However, if all abstract methods are not implemented in the subclass, the subclass must be declared abstract.  classes with all abstract methods are almost exactly like interfaces (what are the differences?)

Graphic view pure impl inheritance mixed impl/ interface inheritance pure interface inheritance regular classinterfaceabstract class Code Reuse polymorphism

Example: InputStream class  java.io.InputStream is a good case-study in abstract classes  InputStream is abstract because int read() is not implemented.  It is up to a subclass of InputStream to implement this method.  FileInputStream one such concrete subclass?  Question: what is the advantage of this structure?