34
Abstract Classes and Interfaces Lecture 2 9/6/2012

Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Embed Size (px)

Citation preview

Page 1: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Abstract Classes and Interfaces

Lecture 2 – 9/6/2012

Page 2: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

2

Objectives Review OOP Concepts Static variables and methods Scope of variables and methods Abstract classes Interfaces Comparing Abstract class and Interfaces

Page 3: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

3

Object Oriented Programming (OOP)

OOP Is a programming paradigm using objects.

Why OOP? We usually think about real world objects, such as a desk, car, student, etc.

Each object has a unique identity, state, and behavior: The state is represented as data fields (class member

variables). The behavior of an object is defined by a set of

methods.

Page 4: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

4

Features of OOP PIE

Polymorphism Polymorphism (from the Greek meaning "having

multiple forms") is the characteristic of being able to assign a different meaning to a particular symbol or "operator" in different contexts.

Difficult to describe, easier to show, so we’ll look at examples later.

Inheritance Encapsulation

Page 5: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

5

Features of OOP PIE

Polymorphism Inheritance

Inheritance is the ability to define a new class in terms of an existing class The existing class is the parent, base or superclass The new class is the child, derived or subclass

The child class inherits all of the attributes and behaviour of its parent class It can then add new attributes or behaviour Or even alter the implementation of existing behaviour (methods)

Avoids defining data fields and methods for a subclass that are may be generic for a set of classes.

This not only speeds up program development; it also ensures an inherent validity to the defined subclass object.

Encapsulation

Page 6: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

6

Features of OOP PIE

Polymorphism Inheritance Encapsulation

The data (state) of an object is private – it cannot be accessed directly. The state can only be changed through its behaviour, otherwise known as its public interface.

The object is said to publish its interfaces. Other objects adhere to these interfaces to use the object without having to be concerned with how the object accomplishes it.

The idea is "don't tell me how you do it; just do it." An object can be thought of as a self-contained atom. The object interface consists of public methods and instantiate data.

Page 7: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

7

Inheritance A subclass has an ‘is a’ relationship to the

parent class. Subclasses absorb the attributes (data fields)

and behaviors (methods) of the parent class and extend these capabilities.

Benefits: Extensibility: New functionality may be easily

plugged in without changing existing classes. Reusability: Reuse core set of data fields and

methods and extended by classes that fill in the application-dependent part.

Page 8: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

8

Inheritance vs. Composition Inheritance implements ‘is a’ relationship. Subclass uses the ‘extends’ keyword to inherit

the attributes and methods of parent class. Ex. A Square is a Shape

Composition implements ‘has a’ relationship A class has objects of other classes as

members Ex. An Employee has a BirthDate Ex. A Square has a Point

Page 9: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

9

Composition Example

Page 10: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

10

Inheritance Example

Page 11: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

11

Visibility Modifiers Java has 4 visibility modifiers

Public Default Private Protected

Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

Page 12: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

12

Class level access modifiers (java classes only) Only two access modifiers is allowed, public

and no modifier (called default)

If class is decalred public, then it CAN be accessed from ANYWHERE.

If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

Page 13: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

13

Member level access modifiers(java variables and java methods) All the 4 public, private, protected and no

modifier is allowed. public

Can be accessed from anywhere no modifier (default)

Can be accessed from the same class or package private

Can be accessed from the same class only protected

Can be accessed from the same package Can be accessed from a subclass existing in any

package

Page 14: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

14

Visibility Modifiers

Access Modifiers

Same Class

Same Package Subclass Other

packages

public Y Y Y Y

protected Y Y Y N

no access modifier Y Y N N

private Y N N N

Page 15: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

15

Instance Variables The data field ‘radius’ in the circle class is called an instance

variable. Instance variables are tied to a specific instance of the class

(not shared among objects of the same class).

class Circle {int radius; // instance variable

public Circle(int r) { radius = r;}

public int getRadius(){ return radius;}

Ex.

Circle c1 = new Circle(5);Circle c2 = new Circle(8);

System.out.println(c1.getRadius()); // 5System.out.println(c2.getRadius()); // 8

Objects c1 and c2 have their own copy of instance variable ‘radius.’

Page 16: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

16

Static Variables Static variables (also called class variables) are shared

among class objects. Ex. We will add a static variable ‘count’ to count the number

of circle objects created. class Circle {

int radius; // instance variablestatic int count = 6;

public Circle(int r) { radius = r; count ++; } public void printCount() { System.out.println(count); }}

Circle c1 = new Circle(5);

c1.printCount(); // 1

Circle c2 = new Circle(8);

c1.printCount(); // 2c2.printCount(); // 2

Circle c3 = new Circle(10);

c1.printCount(); // 3c2.printCount(); // 3c3.printCount(); // 3

All object of class ‘Circle’ share 1 copy of static variable ‘count’.

Page 17: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

17

Static Methods Methods that operate on static variables are declared static

class Circle {

int radius; // instance variablestatic int count = 6; // static variable

public Circle(int r) { radius = r; count ++; } public static void printCount() { System.out.println(count); }}

Method declared static

Page 18: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

18

Static Methods Static methods can be called without creating an instance of

a class. Why? Cause they only operate on static variables.

Circle c1;

Circle.printCount(); // 0

Circle c2 = new Circle(8);

c2.printCount(); // 1

class Circle {

int radius; // instance variablestatic int count = 0; // static variable

public Circle(int r) { radius = r; count += 1; } public static void printCount() { System.out.println(count); }}

Its recommended that you invoke static variables and methods using ClassName.variable and ClassName.method.

Page 19: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Motivation for Abstract Classes Moving up the inheritance chain (from sub-

class to super-class) the classes become more general and describe general/common features.

Shape

Rectangle Circle

getArea();getPerimeter();

getPerimeter() and getCircle() are common features of geometric

objects

getArea();getPerimeter();getRadius();

getArea();getPerimeter();getWidth();getHieght();

19

Page 20: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

20

Abstract Classes An abstract class usually has one method

defined as abstract. An abstract method is a method that has only

its signature defined without its body.

public abstract class Vehicle{ String name;

public String getName() { return name; \\ method body

} public abstract void move();

\\ no body!}

Page 21: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

21

Abstract Classes Abstract class (like regular classes) have data

fields and methods. Unlike regular classes, cannot create an instance

of an abstract class using the new operator. An abstract method is a method signature without

implementation. Any (non-abstract) sub-class of an abstract class,

must provide the implementation of an abstract method.

The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate.

Page 22: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

22

Java Interface

A Java interface is a class-like construct that contains constants and abstract methods since all methods in an interface are abstract,

the abstract modifier is usually left off Methods in an interface have public visibility by

default As with abstract classes, cannot create an

instance of a interface with the new operator

Page 23: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

23

Interface: Syntax

public interface Doable{ public static final String NAME;

public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

interface is a reserved word

No method in aninterface has a definition (body)

Page 24: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

24

Implementing an Interface

A class formally implements an interface by stating so in the class header in the implements

clause a class can implement multiple interfaces: the

interfaces are listed in the implements clause, separated by commas

If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

Page 25: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

25

Implementing Interfaces

public class Something implements Doable{ public void doThis () { // whatever }

public void doThat () { // whatever }

// etc.}

implements is areserved word

Each method listedin Doable is

given a definition

public class ManyThings implements Doable, AnotherDoable

Page 26: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

26

Polymorphism via Interfaces Define a polymorphism reference through

interface declare a reference variable of an interface type

Comparable obj;

the obj reference can be used to point to any object of any class that implements the Comparable interface

the version of compareTo depends on the type of object that obj is referring to:

obj.compareTo();

Page 27: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

27

Interface Hierarchies Inheritance can be applied to interfaces as well as

classes One interface can be used as the parent of

another The child interface inherits all methods of the

parent A class implementing the child interface must

define all methods from both the parent and child interfaces

Page 28: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

28

Interfaces vs. Abstract Classes

variables constructors methods

Abstract No restriction Constructors are invoked by subclasses. Cannot be instantiated using new operator

At least one method must be abstract

Interface All variables must be public static final

No constCannot be instantiated using new operatorConstructor

All methods must be public abstract

Page 29: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

29

Interfaces vs. Abstract Classes (Cont.) Java allows for single inheritance for class

extension, but multiple extensions for interfaces

An interface can inherit other interfaces using the extends keyword.

A class can extend its superclass and implement multiple interfaces.

public class NewClass extends BaseClassimplements Interface1, Interface2, …. InterfaceN

{….}

Page 30: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Abstract Classes & Interfaces

Example Food is an abstract class. Can you make an

instance of food? No. But you can make an instance of an apple or a steak, which are types of food. Food is the abstract concept; it shouldn’t exist.

Skills are ususally interfaces. Can you make an instance of a athlete or chef? No, but you can make an instance of a person, and have that person take on all these skills.

Page 31: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Abstract Classes & Interfaces Q: So what’s the difference between an interface and an

abstract class? A:

An interface cannot implement any methods, whereas an abstract class can.

A class can implement many interfaces but can have only one superclass (abstract or not)

An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Syntax: abstract class:

public class Apple extends Food { … } interface:

public class Person implements Student, Athlete, Chef { … }

Page 32: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Abstract Classes & Interfaces

Q: Why are they useful? A: By leaving certain methods undefined, these methods can be

implemented by several different classes, each in its own way.

Example: Chess Playing Program an abstract class called ChessPlayer can have an abstract method

makeMove(), extended differently by different subclasses.

public abstract class ChessPlayer {<variable declarations><method declarations>public void makeMove(); }

an interface called ChessInterface can have a method called makeMove(), implemented differently by different classes.

public interface ChessInterface {public void makeMove(); }

Page 33: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Abstract Classes & Interfaces

Q: Where else can interfaces be used? A: You can pass an interface as a parameter or assign a

class to an interface variable, just like you would to an abstract class.

Example:

Food myLunch = new Sandwich();

Food mySnack = new Apple();

Student steve = new Person(); //assuming that Person implements Student

If Person has methods eat(Food f) and teach(Student s), the following is possible:

Person bob = new Person();

steve.teach(bob);

steve.eat(myLunch);

System.out.println(“Yum.”);

Page 34: Abstract Classes and Interfaces Lecture 2 – 9/6/2012

34

Examples Look at L2.zip

Shape Example Shape Circle Square Cylinder ShapeTestDriver

Student Example Student Name UnderGrad Grad StudentTestDriver

Employee Example Employee EmployeeTestDriver Name