Lecture 20: Interfaces and Abstract classes

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

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.
Inheritance Inheritance Reserved word protected Reserved word super
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,
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 10 Classes Continued
Object-Orientated Design and Programming Unit 9: Abstract Classes and Interfaces Jin Sa.
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides created by Marty Stepp
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-4: Interfaces reading: self-check: exercises: #11.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
AD Lecture #2 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism Abstract.
CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh) reading: 9.5, 11.1, slides created by Marty Stepp
EE 422C Interfaces Day 5. 2 Announcements SVN has Project 2. –Partly due next week. –SVN update to get it in your repository. See Piazza for Grocery List.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
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.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Building Java Programs Interfaces reading: , 16.4.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Building Java Programs Chapter 9 Interfaces Copyright (c) Pearson All rights reserved.
Lecture 5:Interfaces and Abstract Classes
Inheritance.
Lecture 21: Interfaces and Abstract classes
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)
Modern Programming Tools And Techniques-I
Lecture 23:More on Interfaces
Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2
Web Design & Development Lecture 9
Chapter 15 Abstract Classes and Interfaces
Sixth Lecture ArrayList Abstract Class and Interface
Inheritance ITI1121 Nour El Kadri.
Building Java Programs
Interfaces.
A tree set Our SearchTree class is essentially a set.
Week 4 Object-Oriented Programming (1): Inheritance
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Chapter 13 Abstract Classes and Interfaces
Interfaces EE 422C.
Lecture 23 Polymorphism Richard Gesick.
MSIS 670 Object-Oriented Software Engineering
Interfaces CS163 Fall 2018.
Week 6 Object-Oriented Programming (2): Polymorphism
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh)
A tree set Our SearchTree class is essentially a set.
Java Inheritance.
Shapes Consider the task of writing classes to represent 2D shapes such as Circle, Rectangle, and Triangle. Certain operations are common to all shapes:
Based on slides by Alyssa Harding & Marty Stepp
Lecture 18: Polymorphism (Part II)
Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
CSE 142 Lecture Notes Inheritance, Interfaces, and Polymorphism
Chapter 11 Inheritance and Polymorphism
CSE 373 Implementing a Stack Reading: Weiss Ch. 3; 3.6; 1.5
slides created by Marty Stepp
CSE 143 Lecture 6 interfaces; eclipse; testing
CSE 143 Lecture 21 Advanced List Implementation
Chapter 11 Inheritance and Encapsulation and Polymorphism
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Lecture 20: Interfaces and Abstract classes Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

Interface

Interface Generally, an interface is a shared boundary across which two or more separate components of a computer system exchange information(Wiki) exchange can be between software, peripheral devices, hardware, humans and combinations of these. an interface exposes the functionality of an application or service Examples: an interface between a person and a car’s engine/transmission driving system is the steering wheel, the brake and shift gears. a waiter is an interface between a person and the kitchen of a restaurant. the Facebook phone app is an interface to Facebook’s services.

Interface in Java interface: A list of methods that a class can implement. An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of methods without any implementing code. Inheritance gives you an is-a relationship and code-sharing. A Lawyer object can be treated as an Employee, and Lawyer inherits Employee's code. Interfaces give you an is-a relationship without code sharing. A Rectangle object can be treated as a Shape. Analogous to the idea of roles or certifications: "I'm certified as a CPA accountant. That means I know how to compute taxes, perform audits, and do consulting.” "I'm certified as a Shape. That means I know how to compute my area and perimeter."

Declaring an interface public interface name { public type name(type name, ..., type name); ... } Example: public interface Vehicle { public double speed(); public void setDirection(int direction); abstract method: A header without an implementation. The actual body is not specified, to allow/force different classes to implement the behavior in its own way.

Interface An interface can have only abstract methods. An interface can’t have static methods. An interface supports multiple inheritance. That is, a class can implement multiple interfaces. public class Panel implements MouseListener, ActionListener, KeyboardListener { … } An interface has only static and final variables. An interface cannot have instance variables. Thus, an interface does not have constructors.

Write a set of Circle, Rectangle, and Triangle classes. Relatedness of types Write a set of Circle, Rectangle, and Triangle classes. Certain operations that are common to all shapes. perimeter- distance around the outside of the shape area- amount of 2D space occupied by the shape Every shape has them but computes them differently.

Shape area, perimeter Rectangle (as defined by width w and height h): area = w h perimeter = 2w + 2h Circle (as defined by radius r): area =  r2 perimeter = 2  r Triangle (as defined by side lengths a, b, and c) area = √(s (s - a) (s - b) (s - c)) where s = ½ (a + b + c) perimeter = a + b + c

Common behavior Write shape classes with methods perimeter and area. We'd like to be able to write client code that treats different kinds of shape objects in the same way, such as: Write a method that prints any shape's area and perimeter. Create an array of shapes that could hold a mixture of the various shape objects. Write a method that could return a rectangle, a circle, a triangle, or any other shape we've written.

Shape interface public interface Shape { public double area(); public double perimeter(); } This interface describes the features common to all shapes. (Every shape has an area and perimeter.) These methods are implicitly abstract.

Implementing an interface public class name implements interface { ... } Example: public class Bicycle implements Vehicle { A class can declare that it implements an interface. This means the class must contain each of the abstract methods in that interface. (Otherwise, it will not compile.) (What must be true about the Bicycle class for it to compile?)

Interface requirements If a class claims to be a Shape but doesn't implement the area and perimeter methods, it will not compile. Example: public class Banana implements Shape { ... } The compiler error message: Banana.java:1: Banana is not abstract and does not override abstract method area() in Shape ^

Complete Circle class // Represents circles. public class Circle implements Shape { private double radius; // Constructs a new circle with the given radius. public Circle(double radius) { this.radius = radius; } // Returns the area of this circle. public double area() { return Math.PI * radius * radius; // Returns the perimeter of this circle. public double perimeter() { return 2.0 * Math.PI * radius;

Complete Rectangle class // Represents rectangles. public class Rectangle implements Shape { private double width; private double height; // Constructs a new rectangle with the given dimensions. public Rectangle(double width, double height) { this.width = width; this.height = height; } // Returns the area of this rectangle. public double area() { return width * height; // Returns the perimeter of this rectangle. public double perimeter() { return 2.0 * (width + height);

Complete Triangle class // Represents triangles. public class Triangle implements Shape { private double a; private double b; private double c; // Constructs a new Triangle given side lengths. public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } // Returns this triangle's area using Heron's formula. public double area() { double s = (a + b + c) / 2.0; return Math.sqrt(s * (s - a) * (s - b) * (s - c)); // Returns the perimeter of this triangle. public double perimeter() { return a + b + c;

Interfaces + polymorphism Interfaces don't benefit the class so much as the client. Interface's is-a relationship lets the client use polymorphism. public static void printInfo(Shape s) { System.out.println("The shape: " + s); System.out.println("area : " + s.area()); System.out.println("perim: " + s.perimeter()); } Any object that implements the interface may be passed. Circle circ = new Circle(12.0); Rectangle rect = new Rectangle(4, 7); Triangle tri = new Triangle(5, 12, 13); Shape s1=new Circle(5.0); printInfo(circ); printInfo(tri); printInfo(rect); printInfo(s1); Shape[] shapes = {tri, s1, circ, rect};

Interface diagram Arrow goes up from class to interface(s) it implements. There is a supertype-subtype relationship here; e.g., all Circles are Shapes, but not all Shapes are Circles. This kind of picture is also called a UML class diagram.

Examples Shape[] shapeArray=new Shape[3]; //all null public static void main(){ Shape a=new Shape();//error, can’t create Shape //interface. Shape b=new Circle(); //ok Shape c=new Rectangle(); //ok Shape d=new Triangle(); //ok Shape[] shapeArray=new Shape[3]; //all null shapeArray[0]=b; shapeArray[1]=c; shapeArray[2]=d; ArrayList<Shape> list=new ArrayList<Shape>(); list.add(a); list.add(b); list.add(c,1); list.remove(2); }

Java collections framework

Shape interface

Shape interface The ArrayList class that we have been using implements the List interface from the Java collections framework. public interface List<E> { void add(int index, E element); void add(E element); E get(int index); E remove(int index); } public class ArrayList<E> implements List<E> { // code to implement all of the abstract //methods from List<E>.

Shape interface On the AP Exam, you’ll see the following construction of an arraylist. List<String> myList = new ArrayList<String>(); List<Employee> empList= new ArrayList<Employee>(); myList.add(“Java”); empList.add(new Employee());

Interface Some examples: For example, how does a driver of a car interact or interface with the engine/transmission to drive it? the interface of a car is the steering wheel, the brake and gas pedals and the shift. This interface is simply a list of methods that allow you to interact with your engine/transmission, etc. How does one access the applications on a smart TV? the remote control is the interface that allows a person to interact with their TV. the buttons on the remote are the methods of the interface.

Application Programming Interface an application programming interface(API) is a set of method definitions, protocols, and tools for building application software. In the remote control example, the remote is an “application human interface”. Youtube, Google, and Facebook has API that allows programmers to interact with their software. If you study Facebook’s API, you can write a program that allows someone to interact with facebook while using your program. Or you can use Youtube’s public API to write a program that download, for example, the top 10 most viewed videos of the week.

Abstract Class

Abstract Class An abstract class is a class that is only partially implemented by the programmer. It must be declared abstract. An abstract class may or may not have abstract methods. - An abstract method is that is declared without an implementation. -A class is usually declared abstract if one or more of its methods cannot be implemented and needs to be implemented in a child class. Abstract classes cannot be instantiated(created with new operator). An abstract class can both have instance variables and concrete(nonabstract) methods. An abstract class may or may not have constructors.

Abstract Class Abstract class can be subclassed. When an abstract class is subclassed, the subclass usually provides the implementations for all of the abstract methods. When a subclass doesn’t provide implementations, it must also be declared abstract. Polymorphism works with abstract classes as it does with concrete classes and interfaces.

Example public abstract class Character { private String name; public Character(String name) this.name=name; } //concrete method public String getName() return name; //abstract method public abstract void drawCharacter();

A Subclass public class Mario extends Character { private int numLives; //constructors and other methods not shown. public void drawCharacter() //must provide implementation to draw Mario }} public class Bowser extends Character //must provide implementation to draw Bowser

Examples public static void main(){ //error, can’t create abstract object Character. Character a=new Character(); Character b=new Mario();//ok Bowser c=new Bowser();//ok Character[] CharacterArray=new Shape[2]; CharacterArray[0]=b; CharacterArray[1]=c; ArrayList<Character> list=new ArrayList<Character>(); list.add(b); list.add(c); }

Interface Vs Abstract Class Use an abstract class for an object that is application-specific but incomplete without its subclasses. Use an interface when its methods are suitable for your program but could be equally applicable in a variety of programs. The classes that implement a given interface may represent objects that are vastly different. They, however, all have in common a capability or feature expressed in the methods of the interface. For example, an interface FlyingObject may have methods fly and isFlying. Some classes that implement FlyingObject could be Bird, Airplane, Missile, Butterfly, Witch. Classes that inherit from an abstract(or concrete) class are similar. For example, all subclasses of Employee are “employees”.

Interface Vs Abstract Class An interface cannot provide implementations for any of its methods, whereas an abstract class can. An interface cannot contain instance variables, whereas an abstract class can. An interface can declare final static constants. It is not possible to create an interface object. It is not possible to create an abstract class object.

Interface Vs Abstract Class A class can inherit one one class but can implement multiple interfaces. A class can both inherit and implement interfaces at the same time. In this case, the extends clause must precede the implements clause. public class Fraction extends Number implements Comparable, Computable{ … }

Lab(CS50 IDE) Write an interface called Movable which has four abstract methods: public void moveUp(); public void moveDown(); public void moveLeft(); public void moveRight();

Lab 1 Write a class called MovablePoint which implements Movable. MovablePoint should have private member variables int x and y, one constructor to initialize x and y and an overridden toString method as well as the necessary implementations of the abstract methods from Movable.

Lab 1 Write another class called MovableCircle which also implements Movable. MovableCircle should have private members MovablePoint center and an integer radius, one constructor to initialize the center(with a x1 and y1) and the radius, an overridden toString and any necessary implementations of the abstract methods from Movable.

Lab 1 Write the driver class. Create two Movable objects. One should be a MovablePoint and the other a MovableCircle. Both of these objects must have Movable references. Move the objects and print out their coordinates. Create an array of 2 Movable objects and add the above objects to it. Create an arraylist of 2 Movable objects and add the above objects to it.

Lab 2 Modify Lab 1 at the end of the Polymorphism Lecture # 18 by making the Shape class abstract.