CMSC 132: Object-Oriented Programming II. Interface

Similar documents
Implements vs. Extends When Defining a Class

Java Fundamentals (II)

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CMSC 341. Nilanjan Banerjee

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Generalized Code. Fall 2011 (Honors) 2

ECE 122. Engineering Problem Solving with Java

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Lecture 5: Inheritance

Collections Algorithms

Polymorphism. Agenda

Rules and syntax for inheritance. The boring stuff

First IS-A Relationship: Inheritance

JAVA WRAPPER CLASSES

CMSC 202. Generics II

Chapter 4 Defining Classes I

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

Distributed Systems Recitation 1. Tamim Jabban

Inheritance and Polymorphism

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Introduction to Programming Using Java (98-388)

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance and Polymorphism

Use of the ArrayList class

ITI Introduction to Computing II

What is Inheritance?

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Java Object Oriented Design. CSC207 Fall 2014

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Questions Answer Key Questions Answer Key Questions Answer Key

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Instance Members and Static Members

Inheritance (Part 5) Odds and ends

Example: Count of Points

Introduction to Programming Written Examination

Coverage of Part 2. A Brief Introduction to Java for C++ Programmers: Part 2. import: using packages

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Practice for Chapter 11

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Inheritance and Polymorphism

MIT AITI Lecture 18 Collections - Part 1

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

OOP++ CSE219, Computer Science III Stony Brook University

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Inheritance. Transitivity

COP 3330 Final Exam Review

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

INTERFACE WHY INTERFACE

More Relationships Between Classes

More about inheritance

Inheritance and Interfaces

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

Inheritance (Part 2) Notes Chapter 6

Introduction to Java

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Distributed Systems Recitation 1. Tamim Jabban

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Objects and Iterators

Answer1. Features of Java

Comparing Objects 3/14/16

1 Shyam sir JAVA Notes

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Introduction to Inheritance

CSE 143 Lecture 20. Circle

Inheritance, Polymorphism, and Interfaces

Collections, Maps and Generics

Interfaces, collections and comparisons

Comparing Objects 3/28/16

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

PROGRAMMING FUNDAMENTALS

CS 113 MIDTERM EXAM 2 SPRING 2013

Interfaces. James Brucker

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

CLASS DESIGN. Objectives MODULE 4

PIC 20A Number, Autoboxing, and Unboxing

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CS-202 Introduction to Object Oriented Programming

1. Find the output of following java program. class MainClass { public static void main (String arg[])

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Transcription:

CMSC 132: Object-Oriented Programming II Interface 1

Java Interfaces An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are Java's way of providing much of the power of multiple inheritance without the potential confusion of multiple bases classes having conflicts between method names.. 2

Java Interfaces Is defined by the keyword interface (rather than class) Has only static constants and abstract methods All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier. Notice that an interface is not a class. You cannot create an instance of an interface. 3

Defining an Interface public interface Set<E> { public void insert(e e); public void clear(); public boolean contains(e o); public boolean isempty(); public boolean remove(e o); public int size(); No matter how it is implemented, a Set must have insert, clear, contains, isempty, remove, and size methods 4

Implementing an Interface A class is said to implement an interface if it provides definitions for these methods public class BagSet<E> implements Set<E>{ Now, we may use a BagSet any place that an object of type Set is expected A class implementing an interface can implement additional methods A class can implement several interfaces 5

Interface Example public interface Speaker { public void speak(); class Philosopher extends Human implements Speaker { public void speak(){ public void pontificate() { class Dog extends Animal implements Speaker { public void speak(){ Speaker guest; guest = new Philosopher(); guest.speak(); guest = new Dog(); guest.speak(); 6

Interface Example public interface Rentable{ public int rent(); class House implements Rentable{ public int rent(){ class Car extends Vehicle implements Rentable{ public int rent(){ Rentable r1 = new Car(); Rentable r2 = new House(); 7

Comparable Interfaces The Comparable interface specifies a method called compareto that takes an object as a parameter and returns a negative integer, zero, or a positive integer as the current object is less than, equal to, or greater than the specified object public interface Comparable<T>{ public int compareto(t o); 8

Comparable Interfaces Have we seen classes implementing this interface? Yes! All primitive wrapper classes (String, Integer, Double) implement Comparable By using interfaces a function like Collections.sort() can sort an ArrayList of objects that implement the Comparable interface. For example, an ArrayList of Integers, of Strings, etc. ArrayList<Integer> a = new ArrayList<>(); a.add(10); a.add(5); a.add(20); Collections.sort(a); for(integer i: a){ System.out.print(i+, ); // Output: 5,10,20 9

Comparable Interfaces Can Collections.sort() sort an ArrayList of your own objects (e.g., ArrayList of Students?) Yes! Just make the Students class implement the Comparable interface public interface Comparable<T>{ public int compareto(t o); // Compare students by gpa public class Student implements Comparable<Student>{ public int comparateto(student s2){ return gpa == s2.gpa? 0: gpa> s2.gpa? 1: -1; Can t sort Students if Student is Comparable 10

Multiple Inheritance There are many situations where a simple class hierarchy is not adequate to describe a class structure Example: Suppose that we have our class hierarchy of university people and we also develop a class hierarchy of athletic people: Person AthleticPerson Student Faculty Athlete Coach AthleticDirector HeadCoach AssistantCoach StudentAthlete StudentAthlete: Suppose we want to create an object that inherits all the elements of a Student (admission year, GPA) as well as all the elements of an Athlete (sport, amateur-status) 11

Multiple Inheritance Can we define a StudentAthlete by inheriting all the elements from both Student and Athlete? public class StudentAthlete extends Student, extends Athlete { Alas, no. At least not in Java Nice try! But not allowed in Java Multiple Inheritance: Building a class by extending multiple base classes is called multiple inheritance It is a very powerful programming construct, but it has many subtleties and pitfalls. (E.g., If Athlete and Student both have a name instance variable and a tostring( ) method, which one do we inherit?) Java does not support multiple inheritance. (Although C++ does.) In Java a class can be extended from only one base class However, a class can implement any number of interfaces. 12

Multiple Inheritance with Interfaces Java lacks multiple inheritance, but there is an alternative What public methods do we require of an Athlete object? String getsport( ): Return the athlete s sport boolean isamateur( ): Does this athlete have amateur status? We can define an interface Athlete that contains these methods: public interface Athlete { public String getsport( ); public boolean isamateur( ); Now, we can define a StudentAthlete that extends Student and implements Athlete 13

Multiple Inheritance with Interfaces StudentAthlete extends Student and implements Athlete:public class StudentAthlete extends Student implements Athlete { private String mysport; private boolean amateur; // other things omitted public String getsport( ) { return mysport; public boolean isamateur( ) { return amateur; StudentAthlete can be used: Anywhere that a Student object is expected (because it is derived from Student) Anywhere that an Athlete object is expected (because it implements the public interface of Athlete) So, we have effectively achieved some of the goals of multiple inheritance, by using Java single inheritance mechanism 14

Common Uses of Interfaces Interfaces are flexible things and can be used for many purposes in Java: A work-around for Java s lack of multiple inheritance. (We have just seen this.) Specifying minimal functional requirements for classes (This is its principal purpose.) For defining groups of related symbolic constants. (This is a somewhat unexpected use, but is not uncommon.) 15

Using Interfaces for Symbolic Constants In addition to containing method declarations, interfaces can contain constants, that is, variables that are public final static. interface OlympicMedal { static final String GOLD = "Gold"; static final String SILVER = "Silver"; static final String BRONZE = "Bronze"; Considered bad practice. 16

Default Methods Java 8 introduces Default Method, a new feature Add new methods to the interfaces without breaking the existing implementation of these interface. public interface A { public void m1(); default public void m2 { println("default m2 ; public class B implements A { public void m1() { B b = new B(); b.m2(); // print default m2 17

Abstract classes versus interfaces After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8. Abstract class can define constructor. They can have a state associated with them. default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Both use for different purposes and choosing between two really depends on the scenario context. 18

Multiple Inheritance Ambiguity Problems Since java class can implement multiple interfaces and each interface can define default method with same method signature, therefore, the inherited methods can conflict with each other. public interface A { default int m1(){ return 1; public interface B { default int m1(){ Return 2; public class C implements A, B { A:m1 C:m1 B:m1 This code will fail to compile 19

Interface Hierarchies Inheritance applies to interfaces, just as it does to classes. When an interface is extended, it inherits all the previous methods 20

Quiz 1: True /False An interface can contain following type of members: public, static, final fields (i.e., constants) default and static methods with bodies A. True B. False 21

Quiz 1: True /False An interface can contain following type of members: public, static, final fields (i.e., constants) default and static methods with bodies A. True B. False 22

Quiz 2: True /False A class can implement multiple interfaces and many classes can implement the same interface. A. True B. False 23

Quiz 2: True /False A class can implement multiple interfaces and many classes can implement the same interface. A. True B. False 24

Quiz 3: What is the output? abstract class Demo{ public int a; public Demo(){ a = 10; abstract public void set(); abstract final public void get(); class Test extends Demo{ public void set(int a){this.a = a; final public void get(){ System.out.println("a = " + a); public static void main(string[] args){ Test obj = new Test(); obj.set(20); obj.get(); A. a = 10 B. a = 20 C. Compile error 25

Quiz 3: What is the output? abstract class Demo{ public int a; public Demo(){ a = 10; abstract public void set(); abstract final public void get(); class Test extends Demo{ public void set(int a){this.a = a; final public void get(){ System.out.println("a = " + a); public static void main(string[] args){ Test obj = new Test(); obj.set(20); obj.get(); Final method can t be overridden. Thus, an abstract function can t be final. A. a = 10 B. a = 20 C. Compile error 26

Quiz 4: Can an interface extend another interface? A. No. Only classes can be extended. B. No. Interfaces can not be part of a hierarchy. C. Yes. Since all interfaces automatically extend Object. D. Yes. 27

Quiz 4: Can an interface extend another interface? A. No. Only classes can be extended. B. No. Interfaces can not be part of a hierarchy. C. Yes. Since all interfaces automatically extend Object. D. Yes. 28

Quiz 5: Can an interface be given the private access modifier? A. No. Then the interface could never be used. B. No. Since only private classes could use the interface. C. Yes. This would make all of its methods and constants private. D. Yes. This would mean that only classes in the same file could use the interface. 29

Quiz 5: Can an interface be given the private access modifier? A. No. Then the interface could never be used. B. No. Since only private classes could use the interface. C. Yes. This would make all of its methods and constants private. D. Yes. This would mean that only classes in the same file could use the interface. 30