The Interface Concept



Similar documents
Java Interview Questions and Answers

Introduction to Object-Oriented Programming

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Part I. Multiple Choice Questions (2 points each):

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

History OOP languages Year Language 1967 Simula Smalltalk

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Java from a C perspective. Plan

AP Computer Science Java Subset

Chapter 2 Introduction to Java programming

CS 111 Classes I 1. Software Organization View to this point:

Programming Methods & Java Examples

Fundamentals of Java Programming

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Chapter 13 - Inheritance

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Programming Languages Featherweight Java David Walker

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Lecture J - Exceptions

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Introduction to Object-Oriented Programming

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

C++ INTERVIEW QUESTIONS

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

INPUT AND OUTPUT STREAMS

public static void main(string[] args) { System.out.println("hello, world"); } }

Java Programming Language

Software Engineering Techniques

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

CS193j, Stanford Handout #10 OOP 3

Chapter 1 Fundamentals of Java Programming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java (12 Weeks) Introduction to Java Programming Language

Crash Course in Java

Overview. What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test?

11 November

Chapter 1 Java Program Design and Development

Contents. 9-1 Copyright (c) N. Afshartous

Inheritance, overloading and overriding

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

java Features Version April 19, 2013 by Thorsten Kracht

Using Files as Input/Output in Java 5.0 Applications

CMSC 202H. ArrayList, Multidimensional Arrays

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

J a v a Quiz (Unit 3, Test 0 Practice)

Construction of classes with classes

Example of a Java program

WRITING DATA TO A BINARY FILE

Java Programming Fundamentals

AVRO - SERIALIZATION

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Using Inheritance and Polymorphism

Computing Concepts with Java Essentials

Building a Multi-Threaded Web Server

Web Development and Core Java Lab Manual V th Semester

El Dorado Union High School District Educational Services

Introduction: Abstract Data Types and Java Review

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Data Structures in the Java API

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java Crash Course Part I

Abstraction and Abstract Data Types

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

An Overview of Java. overview-1

Interactive Applications (CLI) and Math

D06 PROGRAMMING with JAVA

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Enumerated Types in Java

Specialized Programme on Web Application Development using Open Source Tools

CS170 Lab 11 Abstract Data Types & Objects

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

2. Conceptual Modeling using the Entity-Relationship Model

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Basic Object-Oriented Programming in Java

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

D06 PROGRAMMING with JAVA

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Advanced OOP Concepts in Java

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Transcription:

Multiple inheritance Interfaces Four often used Java interfaces Iterator Cloneable Serializable Comparable The Interface Concept OOP: The Interface Concept 1

Multiple Inheritance, Example Person name() cpr() For the teaching assistant when want the properties from both Employee and Student. Employee salary() degree() Student gpa() courses() Teaching A. OOP: The Interface Concept 2

Employee Problems with Multiple Inheritance department Person name() cpr() TeachingA. Student department ta = new TeachingAssistant(); ta.department; Name clash problem: Which department does ta refers to? Combination problem: Can department from Employee and Student be combined in Teaching Assistant? Selection problem: Can you select between department from Employee and department from Student? Replication problem: Should there be two departments in TeachingAssistent? OOP: The Interface Concept 3

Multiple Classifications Object Comparable Runnable Serializable Cloneable X Y Multiple and overlapping classification for the classes X and Y, i.e., class X is Runnable and Comparable class Y is Runnable, Serializable, and Cloneable OOP: The Interface Concept 4

Java's interface Concept Shape draw() resize() Interface Circle draw() resize() implements Line draw() resize() Rectangle draw() resize() extends Square draw() resize() OOP: The Interface Concept 5

Java's interface Concept, cont. public interface Shape { double PI = 3.14; // static and final => upper case void draw(); // automatic public void resize(); // automatic public public class Rectangle implements Shape { public void draw() {System.out.println ("Rectangle"); public void resize() { /* do stuff */ public class Square extends Rectangle { public void draw() {System.out.println ("Square"); public void resize() { /* do stuff */ OOP: The Interface Concept 6

Java's interface Concept An interface is a collection of method declarations. An interface is a class-like concept. An interface has no variable declarations or method bodies. Describes a set of methods that a class can be forced to implement. An interface can be used to define a set of constant. An interface can be used as a type concept. Variable and parameter can be of interface types. Interfaces can be used to implement multiple inheritance like hierarchies. OOP: The Interface Concept 7

Java's interface Concept, cont. interface InterfaceName { // "constant" declarations // method declarations // inheritance between interfaces interface InterfaceName extends InterfaceName {... // not possible interface InterfaceName extends InterfaceName1, InterfaceName2 {... // not possible interface InterfaceName extends ClassName {... OOP: The Interface Concept 8

Java's interface Concept, cont. // implements instead of extends class ClassName implements InterfaceName {... // multiple inheritance like class ClassName implements InterfaceName1, InterfaceName2 {... // combine inheritance and interface implementation class ClassName extends SuperClass implements InterfaceName {... // multiple inheritance like again class ClassName extends SuperClass implements InterfaceName1, InterfaceName2 {... OOP: The Interface Concept 9

Type Semantic Rules for Interfaces An interface can be used as a type, like classes A variable or parameter declared of an interface type is polymorph Any object of a class that implements the interface can be referred by the variable Instantiation Does not make sense on an interface. Access modifiers An interface can be public or friendly (the default). All methods in an interface are default abstract and public. Static, final, private, and protected cannot be used. All variables ( constants ) are public static final by default Private, protected cannot be used. OOP: The Interface Concept 10

Iterator Some of Java's Most used Interfaces To run through a collection of objects without knowing how the objects are stored, e.g., in array, list, bag, or set. More on this in the lecture on the Java collection library. Cloneable To make a copy of an existing object via the clone() method on the class Object. More on this topic in todays lecture. Serializable Pack a web of objects such that it can be send over a network or stored to disk. An naturally later be restored as a web of objects. More on this in the lecture on Java's I/O system Comparable To make a total order on objects, e.g., 3, 56, 67, 879, 3422, 34234 More on this topic in todays lecture. OOP: The Interface Concept 11

The Iterator Interface The Iterator interface in the package java.util is a basic iterator that works on collections. package java.util; public interface Iterator { // the full meaning is public abstract boolean hasnext() boolean hasnext(); Object next(); void remove(); // optional throws exception // use an iterator myshapes = getsomecollectionofshapes(); Iterator iter = myshapes.iterator(); while (iter.hasnext()) { Shape s = (Shape)iter.next(); // downcast s.draw(); OOP: The Interface Concept 12

The Cloneable Interface A class X that implements the Cloneable interface tells clients that X objects can be cloned. The interface is empty, i.e., has no methods. Returns an identical copy of an object. A shallow copy, by default. A deep copy is often preferable. Prevention of cloning Necessary if unique attribute, e.g., database lock or open file reference. Not sufficient to omit to implement Cloneable. Subclasses might implement it. clone method should throw an exception: CloneNotSupportedException OOP: The Interface Concept 13

The Cloneable Interface, Example // Car example revisited public class Car implements Cloneable{ private String make; private String model; private double price; // default constructor public Car() { this("", "", 0.0); // give reasonable values to instance variables public Car(String make, String model, double price){ this.make = make; this.model = model; this.price = price; // the Cloneable interface public Object clone(){ return new Car(this.make, this.model, this.price); OOP: The Interface Concept 14

The Serializable Interface A class X that implements the Serializable interface tells clients that X objects can be stored on file or other persistent media. The interface is empty, i.e., has no methods. public class Car implements Serializable { // rest of class unaltered snip // write to and read from disk import java.io.*; public class SerializeDemo{ Car mytoyota, anothertoyota; mytoyota = new Car("Toyota", "Carina", 42312); ObjectOutputStream out = getoutput(); out.writeobject(mytoyota); ObjectInputStream in = getinput(); anothertoyota = (Car)in.readObject(); OOP: The Interface Concept 15

The Comparable Interface In the package java.lang. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. package java.lang; public interface Comparable { int compareto(object o); OOP: The Interface Concept 16

The Comparable Interface, Example // IPAddress example revisited public class IPAddress implements Comparable{ private int[] n; // here IP stored, e.g., 125.255.231.123 /** The Comparable interface */ public int compareto(object o){ IPAddress other = (IPAddress) o; // downcast int result = 0; for(int i = 0; i < n.length; i++){ if (this.getnum(i) < other.getnum(i)){ result = -1; break; if (this.getnum(i) > other.getnum(i)){ result = 1; break; return result; OOP: The Interface Concept 17

Interface vs. Abstract Class Interface Methods can be declared No method bodies Constants can be declared Has no constructors Multiple inheritance possible Has no top interface Multiple parent interfaces Abstract Class Methods can be declared Method bodies can be defined All types of variables can be declared Can have constructors Multiple inheritance not possible Always inherits from Object Only one parent class OOP: The Interface Concept 18

Interfaces and Classes Combined By using interfaces objects do not reveal which classes the belong to. With an interface it is possible to send a message to an object without knowing which class(es) it belongs. The client only know that certain methods are accessible. By implementing multiple interfaces it is possible for an object to change role during its life span. Design guidelines Use classes for specialization and generalization Use interfaces to add properties to classes. OOP: The Interface Concept 19

Multiple Inheritance vs. Interface Multiple Inheritance Declaration and definition is inherited. Little coding to implement subclass. Hard conflict can exist. Very hard to understand (C++ close to impossible). Flexible Interface Only declaration is inherited. Must coding to implement an interface. No hard conflicts. Fairly easy to understand. Very flexible. Interface totally separated from implementation. OOP: The Interface Concept 20

Summary Purpose: Interfaces and abstract classes can be used for program design, not just program implementation [Meyer pp 239 ff]. Java only supports single inheritance. Java fakes multiple inheritance via interfaces. Very flexible because the object interface is totally separated from the objects implementation. OOP: The Interface Concept 21

The Cloneable Interface, Example 2 package geometric; // [Source: java.sun.com] /** A cloneable Point */ public class Point extends java.awt.point implements Cloneable { // the Cloneable interface public Object clone(){ try { return (super.clone()); // protected in Object // must catch exception will be covered later catch (CloneNotSupportedException e){ return null; public Point(int x, int y){ super(x,y); OOP: The Interface Concept 22