CMSC 202 Interfaces.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Unit 031 Interfaces What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces.
CS102--Object Oriented Programming Lecture 15: Interfaces Copyright © 2008 Xiaoyan Li.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
I NTERFACES Prepared by Miss Simab Shahid Lecturer computer Science and Software Engineering department, University of Hail Chapter.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Java Interfaces. Interfaces An interface is something like an extreme case of an abstract class – However, an interface is not a class – It is a type.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Interfaces An interface is like an extreme case of an abstract class – However, an interface is not a class – It is a type that can be satisfied by any.
Interfaces and Inner Classes
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
UNIT-3 Interfaces & Packages. What is an Interface? An interface is similar to an abstract class with the following exceptions: All methods defined in.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 7 : Interfaces King Fahd University of Petroleum & Minerals College of Computer.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
CMSC 202 ArrayList Aug 9, 2007.
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Comp 249 Programming Methodology
CMSC 202 Static Methods.
Inheritance 2nd Lecture
Polymorphism 2nd Lecture
Interface.
CMSC 202 Interfaces.
CMSC 202 Polymorphism.
Inheritance 2nd Lecture
CMSC 202 ArrayList Aug 9, 2007.
Classes and Objects 5th Lecture
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Lecture 16 - Interfaces Professor Adams.
Java Classes and Objects 3rd Lecture
CSE 1030: Implementing GUI Mark Shtern.
Interfaces and Inner Classes
CMSC 202 ArrayList Aug 9, 2007.
Inheritance 2nd Lecture
Java Inheritance.
مظفر بگ محمدی دانشگاه ایلام
Java Classes and Objects
CMSC 202 Classes and Objects.
CMSC 202 Generics.
Classes and Objects Static Methods
TCSS 143, Autumn 2004 Lecture Notes
Chapter 13 Abstract Classes and Interfaces Part 01
CMSC 202 Inheritance II.
CMSC 202 Exceptions.
CMSC 202 Interfaces.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CMSC 202 Interfaces

Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method. These public methods form the class’ interface . An abstract class contains one or more methods with only an interface – no method body is provided. Java allows us to take this concept one step further. Aug 7, 2007

Interfaces An interface is something like an extreme abstract class. All of the methods in an interface are abstract – they have no implementations. An interface has no instance variables. Only defines methods. is NOT a class. is a type that can be satisfied by any class that implements the interface Aug 7, 2007

Copyright © 2008 Pearson Addison-Wesley. Interfaces The syntax for defining an interface is similar to that of defining a class Except the word interface is used in place of class An interface specifies a set of methods that any class that implements the interface must have It contains method headings (and optionally static final constant definitions) only It contains no instance variables nor any complete method definitions Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 4

Copyright © 2008 Pearson Addison-Wesley. Interfaces An interface and all of its method headings should be declared public They cannot be given private, protected, or package access When a class implements an interface, it must make all the methods in the interface public. Because an interface is a type, a method may be written with a parameter of an interface type That parameter will accept as an argument any class that implements the interface Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 5

Implementing an Interface To create a class that implements all the methods defined in an interface, use the keyword implements. Whereas interface defines the headings for methods that must be defined, a class that implements the interface defines how the methods work. Aug 7, 2007

The Animal Interface public interface Animal { public void eat( ); } Yes, animals do more than eat, but we’re trying to make this a simple example. Aug 7, 2007

implements Interface_Name Interfaces To implement an interface, a concrete class must do two things: It must include the phrase implements Interface_Name at the start of the class definition If more than one interface is implemented, each is listed, separated by commas The class must implement all the method headings listed in the definition(s) of the interface(s) Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 8

Implementing Animal public class Snake implements Animal // Lion and Snake implement the required eat( ) method public class Lion implements Animal { public void eat() { System.out.println("Lions Devour"); } } public class Snake implements Animal { System.out.println( "Snakes swallow whole"); } Aug 7, 2007

Implementing Animal // Dog implements the required eat( ) method and has // some of its own methods and instance variables public class Dog implements Animal { private String name; Dog(String newName) {name = newName;} public void eat() {System.out.println("Dog chews a bone");} } // Poodle is derived from Dog, so it inherits eat( ) // Adds a method of its own public class Poodle extends Dog { Poodle( String name ) { super(name); } // call Dog constructor public String toString( ) { return "Poodle"; } Aug 7, 2007

Implementing Animal // --- Output Lions Devour Dog chews a bone // Using classes that implement Animal public class Jungle { public static void feed( Animal a ) { a.eat(); } public static void main( String[] args ){ Animal[ ] animals = { new Lion( ), new Poodle( "Fluffy“ ), new Dog( "Max“ ), new Snake( ) }; for (int i = 0; i < animals.length; i++) feed( animals[ i ] ); } // --- Output Lions Devour Dog chews a bone Snakes swallow whole

Extending an Interface An new interface can add method definitions to an existing interface by extending the old interface TiredAnimal extends Animal { public void sleep( ); } The TiredAnimal interface includes both eat( ) and sleep( ); Aug 7, 2007

Interface Semantics Are Not Enforced When a class implements an interface, the compiler and run-time system check the syntax of the interface and its implementation However, neither checks that the body of an interface is consistent with its intended meaning Required semantics for an interface are normally added to the documentation for an interface It then becomes the responsibility of each programmer implementing the interface to follow the semantics If the method body does not satisfy the specified semantics, then software written for classes that implement the interface may not work correctly Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 13

The Comparable Interface The Comparable interface is in the java.lang package, and so is automatically available to any program It has only the following method heading that must be implemented (note the Object parameter) public int compareTo(Object other); It is the programmer's responsibility to follow the semantics of the Comparable interface when implementing it When implementing compareTo, you would of course overload it by using an appropriate parameter type Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 14

The Comparable Interface Semantics The method compareTo must return A negative number if the calling object "comes before" the parameter other A zero if the calling object "equals" the parameter other A positive number if the calling object "comes after" the parameter other If the parameter other is not of the same type as the class being defined, then a ClassCastException should be thrown Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 15

The Comparable Interface Semantics Almost any reasonable notion of "comes before" is acceptable In particular, all of the standard less-than relations on numbers and lexicographic ordering on strings are suitable The relationship "comes after" is just the reverse of "comes before" Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 16

compareTo for Person public class Person implements Comparable { private String name; ... int compareTo( Object obj ) Person p = (Person)obj; return name.compareTo(p.name); } .... If obj is not a Person object a ClassCastException will be thrown Comparing the names using String’s compareTo method Aug 7, 2007

Using Comparable // prints the index of the smallest Integer in an array // Note use of Integer, not int public class FindSmallest { public static void main( String[ ] args) { // find the smallest Integer in an array // Integer (implements Comparable int index = 0; // index of smallest value Integer[ ] values = { new Integer(144), new Integer(200), new Integer(99), new Integer(42), new Integer(132) }; for (int i = 1; i < values.length; i++) if ( values[ i ].compareTo( values[ index ] ) < 0 ) index = i; } System.out.println("Index of smallest value is “ + index); Aug 7, 2007

Defined Constants in Interfaces An interface can contain defined constants in addition to, or instead of, method headings Any variables defined in an interface must be public, static, and final Because this is understood, Java allows these modifiers to be omitted Any class that implements the interface has access to these defined constants Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 19

Constants in an Interface enums (as in C/C++) were not available prior to Java 5. To model enums, interfaces containing (public static final) constants were used public interface Months { int JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12; } Reference the constants as Months.JANUARY Aug 7, 2007

Implementing Multiple Interfaces Recall the Animal interface from earlier public interface Animal { public void eat( ); } Define the Cat interface public interface Cat void purr( ); // public by default; // since a Lion is an Animal and a Cat, Lion may wish // to implement both interfaces public class Lion implements Animal, Cat public void eat( ) {System.out.println(“Big Gulps”);} public void purr( ) {System.out.println(“ROOOAAAR!”);} Just separate the Interface names with a comma Aug 7, 2007

Inconsistent Interfaces In Java, a class can have only one base class This prevents any inconsistencies arising from different definitions having the same method heading In addition, a class may implement any number of interfaces Since interfaces do not have method bodies, the above problem cannot arise However, there are other types of inconsistencies that can arise Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 22

Inconsistent Interfaces When a class implements two interfaces: One type of inconsistency will occur if the interfaces have constants with the same name, but with different values Another type of inconsistency will occur if the interfaces contain methods with the same name but different return types If a class definition implements two inconsistent interfaces, then that is an error, and the class definition is illegal Aug 7, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 23