Abstract Class & Java Interface



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

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

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

Java Programming Language

Java Interview Questions and Answers

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

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

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

Chapter 1 Fundamentals of Java Programming

CS193j, Stanford Handout #10 OOP 3

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

Chapter 13 - Inheritance

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

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

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Description of Class Mutation Mutation Operators for Java

Object-Oriented Programming: Polymorphism

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

Object-Oriented Programming Lecture 2: Classes and Objects

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

The Interface Concept

History OOP languages Year Language 1967 Simula Smalltalk

AP Computer Science Java Subset

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Inheritance, overloading and overriding

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

C++ INTERVIEW QUESTIONS

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

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

Using Inheritance and Polymorphism

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

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

Java Application Developer Certificate Program Competencies

Fundamentals of Java Programming

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

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

Habanero Extreme Scale Software Research Project

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

Introducing Variance into the Java Programming Language DRAFT

Software Construction

Advanced Data Structures

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

Design Patterns in Java

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Java (12 Weeks) Introduction to Java Programming Language

Programming Languages Featherweight Java David Walker

D06 PROGRAMMING with JAVA

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

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

Embedded Software development Process and Tools: Lesson-1

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

Basic Object-Oriented Programming in Java

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

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

Stack Allocation. Run-Time Data Structures. Static Structures

Building Java Programs

16 Collection Classes

Reusing Classes in Java. Java - Inheritance/Polymorphism/Interface. Simple Example of Composition. Inheritance. Composition.

Towards Interface Types for Haskell

Web Development in Java

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

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

5. Advanced Object-Oriented Programming Language-Oriented Programming

Class 16: Function Parameters and Polymorphism

Introduction: Abstract Data Types and Java Review

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

Specialized Programme on Web Application Development using Open Source Tools

3 Improving the Crab more sophisticated programming

LAB4 Making Classes and Objects

Checking Access to Protected Members in the Java Virtual Machine

Lecture 9. Semantic Analysis Scoping and Symbol Table

CIS 190: C/C++ Programming. Polymorphism

Constructor, Destructor, Accessibility and Virtual Functions

Stack vs. Heap. Introduction to Programming. How the Stack Works. Primitive vs. Reference Types. Stack

Course MS10975A Introduction to Programming. Length: 5 Days

Specialized Programme on Web Application Development using Open Source Tools

11 November

Object-Oriented Programming in Java

Tutorial on Writing Modular Programs in Scala

Java CPD (I) Frans Coenen Department of Computer Science

Konzepte objektorientierter Programmierung

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Java Classes. GEEN163 Introduction to Computer Programming

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Object-Oriented Programming

Programming and Software Development CTAG Alignments

A power series about x = a is the series of the form

Twin A Design Pattern for Modeling Multiple Inheritance

JAVA - OBJECT & CLASSES

TypeScript for C# developers. Making JavaScript manageable

Limitations of Data Encapsulation and Abstract Data Types

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

Transcription:

Abstract Class & Java Interface 1

Agenda What is an Abstract method and an Abstract class? What is Interface? Why Interface? Interface as a Type Interface vs. Class Defining an Interface Implementing an Interface Implementing multiple Interface's Inheritance among Interface's Interface and Polymorphism Rewriting an Interface 2

What is an Abstract Class? 3

Abstract Methods Methods that do not have implementation (body) To create an abstract method, just write the method declaration without the body and use the abstract keyword No { } For example, // Note that there is no body public abstract void somemethod(); 4

Abstract Class An abstract class is a class that contains one or more abstract methods An abstract class cannot instantiated // You will get a compile error on the following code MyAbstractClass a1 = new MyAbstractClass(); Another class (Concrete class) has to provide implementation of abstract methods Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation Concrete class uses extends keyword 5

Sample Abstract Class public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } } /** * Abstract method walk() * We want this method to be implemented by a * Concrete class. */ public abstract void walk(); 6

Extending an Abstract Class When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated. For example, public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } } 7

When to use Abstract Methods & Abstract Class? Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. 8

What is Interface? 9

What is an Interface? It defines a standard and public way of specifying the behavior of classes Defines a contract All methods of an interface are abstract methods Defines the signatures of a set of methods, without the body (implementation of the methods) A concrete class must implement the interface (all the abstract methods of the Interface) It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors 10

Example: Interface // Note that Interface contains just set of method // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. public interface Relation { public boolean isgreater( Object a, Object b); public boolean isless( Object a, Object b); public boolean isequal( Object a, Object b); } 11

Example 2: OperatorCar Interface public interface OperateCar { // constant declarations, if any } // method signatures int turn(direction direction, double radius, double startspeed, double endspeed); int changelanes(direction direction, double startspeed, double endspeed); int signalturn(direction direction, boolean signalon); int getradarfront(double distancetocar, double speedofcar); int getradarrear(double distancetocar, double speedofcar);... // more method signatures 12

Why Interface? 13

Why do we use Interfaces? Reason #1 To reveal an object's programming interface (functionality of the object) without revealing its implementation This is the concept of encapsulation The implementation can change without affecting the caller of the interface The caller does not need the implementation at the compile time It needs only the interface at the compile time During runtime, actual object instance is associated with the interface type 14

Why do we use Interfaces? Reason #2 To have unrelated classes implement similar methods (behaviors) One class is not a sub-class of another Example: Class Line and class MyInteger They are not related through inheritance You want both to implement comparison methods checkisgreater(object x, Object y) checkisless(object x, Object y) checkisequal(object x, Object y) Define Comparison interface which has the three abstract methods above 15

Why do we use Interfaces? Reason #3 To model multiple inheritance A class can implement multiple interfaces while it can extend only one class 16

Interface vs. Abstract Class All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods Abstract methods of abstract class have abstract modifier An interface can only define constants while abstract class can have fields Interfaces have no direct inherited relationship with any particular class, they are defined independently Interfaces themselves have inheritance relationship among themselves 17

Interface as a Type 18

Interface as a Type When you define a new interface, you are defining a new reference type You can use interface names anywhere you can use any other type name If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface 19

Example: Interface as a Type Let's say Person class implements PersonInterface interface You can do Person p1 = new Person(); PersonInterface pi1 = p1; PersonInterface pi2 = new Person(); 20

Interface vs. Class 21

Interface vs. Class: Commonality Interfaces and classes are both types This means that an interface can be used in places where a class can be used For example: // Recommended practice PersonInterface // Not recommended practice Person pi = new Person(); pc = new Person(); Interface and Class can both define methods 22

Interface vs. Class: Differences The methods of an Interface are all abstract methods They cannot have bodies You cannot create an instance from an interface For example: PersonInterface pi = new PersonInterface(); //ERROR! An interface can only be implemented by classes or extended by other interfaces 23

Defining Interface 24

Defining Interfaces To define an interface, we write: public interface [InterfaceName] { } //some methods without the body 25

Defining Interfaces As an example, let's create an interface that defines relationships between two objects according to the natural order of the objects. public interface Relation { public boolean isgreater( Object a, Object b); public boolean isless( Object a, Object b); public boolean isequal( Object a, Object b); } 26

Implementing Interface 27

Implementing Interfaces To create a concrete class that implements an interface, use the implements keyword. /** * Line class implements Relation interface */ public class Line implements Relation { private double x1; private double x2; private double y1; private double y2; public Line(double x1, double x2, double y1, double y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } // More code follows 28

Implementing Interfaces public double getlength(){ double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)); return length; } public boolean isgreater( Object a, Object b){ double alen = ((Line)a).getLength(); double blen = ((Line)b).getLength(); return (alen > blen); } public boolean isless( Object a, Object b){ double alen = ((Line)a).getLength(); double blen = ((Line)b).getLength(); return (alen < blen); } } public boolean isequal( Object a, Object b){ double alen = ((Line)a).getLength(); double blen = ((Line)b).getLength(); return (alen == blen); } 29

Implementing Interfaces When your class tries to implement an interface, always make sure that you implement all the methods of that interface, or else, you would encounter this error, Line.java:4: Line is not abstract and does not override abstract method isgreater(java.lang.object,java.lang.object) in Relation public class Line implements Relation 1 error ^ 30

Implementing Class Implementing class can have its own methods Implementing class extend a single super class or abstract class 31

Implementing Multiple Interfaces 32

Relationship of an Interface to a Class A concrete class can only extend one super class, but it can implement multiple Interfaces The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative. All abstract methods of all interfaces have to be implemented by the concrete class 33

Example: Implementing Multiple Interfaces A concrete class extends one super class but multiple Interfaces: public class ComputerScienceStudent extends Student implements PersonInterface, AnotherInterface, Thirdinterface{ } // All abstract methods of all interfaces // need to be implemented. 34

Inheritance Among Interfaces 35

Inheritance Among Interfaces Interfaces are not part of the class hierarchy However, interfaces can have inheritance relationship among themselves public interface PersonInterface { void dosomething(); } public interface StudentInterface extends PersonInterface { void doextrasomething(); } 36

Interface & Polymorphism 37

Interface and Polymorphism Interfaces exhibit polymorphism as well, since program may call an interface method, and the proper version of that method will be executed depending on the type of object instance passed to the interface method call 38

Rewriting Interfaces 39

Problem of Rewriting an Existing Interface Consider an interface that you have developed called DoIt: public interface DoIt { void dosomething(int i, double x); int dosomethingelse(string s); } Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: public interface DoIt { void dosomething(int i, double x); int dosomethingelse(string s); boolean diditwork(int i, double x, String s); } If you make this change, all classes that implement the old DoIt interface will break because they don't implement all methods of the the interface anymore 40

Solution of Rewriting an Existing Interface Create more interfaces later For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean diditwork(int i, double x, String s); } Now users of your code can choose to continue to use the old interface or to upgrade to the new interface 41

When to Use an Abstract Class over an Interface? 42

When to use an Abstract Class over Interface? For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes Reducing the duplication For abstract methods, the motivation is the same with the ones in the interface to impose a common behavior for all sub-classes without dictating how to implement it Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class 43

Abstract Class & Java Interface 44