Sie sind auf Seite 1von 30

Object-Oriented Programming

Lecture 4: Interfaces & Inheritance


Dr. L H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH

July 2012
1

Tuesday, July 31, 12


Content

Interfaces Inheritance

Defining an interface Overriding and hiding


methods
Implementing an interface
Polymorphism
Using an interface as a type
Object as a super class
Rewriting interfaces
Final classes and methods

Abstract methods and classes

Tuesday, July 31, 12


Defining an interface

public interface GroupedInterface extends Interface1, Interface2, Interface3 {


// base of natural logarithms
double E = 2.718282;

// method signatures
void doSomething(int i, double x);

int doSomethingElse(String s);


}

If an interface is not declared public, it will be accessible only to


classes defined in the same package as the interface.

A class can extend only one other class, an interface can extend any
number of interfaces.

An interface can also contain constant declarations.


3

Tuesday, July 31, 12


Implementing an interface
public interface Relatable {
public int isLargerThan(Relatable other);
}

public class Person implements Relatable {


double weight;

public Person(double w) {



}
weight = w;
Implement the


public double getWeight() {
return weight;
required method
}
public int isLargerThan(Relatable other) {
Person person = (Person) other;
if (this.getWeight() < person.getWeight())
return -1;
else if (this.getWeight() > person.getWeight())
return 1;
else



}
return 0; Note the casting
}
4

Tuesday, July 31, 12


Implementing an interface
public class RectanglePlus implements Relatable {
int width = 0;
int height = 0;
Point origin;

public RectanglePlus(Point p, int w, int h) {


origin = p;
width = w;
height = h; Implement the
}
public int getArea() { required method
return width * height;
}
public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus) other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}
5

Tuesday, July 31, 12


Using an interface as a type

An interface is a reference data type.

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.
public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}

Tuesday, July 31, 12


Rewriting interfaces

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:
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x, String s);
}

Tuesday, July 31, 12


Rewriting interfaces

If you make this change, all classes that implement the old DoIt
interface will break because they dont implement the interface
anymore.

Programmers rely on this interface will protest loudly.

You should 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 upgrade to the new one.

Tuesday, July 31, 12


Another example of interfaces
/** Describes any class whose objects can be measured. */
public interface Measurable {
/**
* Computes the measure of the object.
*
* @return the measure
*/
double getMeasure();
}

/** Describes any class whose objects can measure other objects. */
public interface Measurer {
/**
* Computes the measure of an object.
*
* @param anObject the object to be measured
* @return the measure
*/
double measure(Object anObject);
}
9

Tuesday, July 31, 12


Content

Interfaces Inheritance

Defining an interface Overriding and hiding


methods
Implementing an interface
Polymorphism
Using an interface as a type
Object as a super class
Rewriting interfaces
Final classes and methods

Abstract methods and classes

10

Tuesday, July 31, 12


Inheritance
A class that is derived from another class is called a subclass (also a derived
class, extended class, child class).

The superclass is also called base class or parent class.

In Java, excepting Object, every class has one and only one direct
superclass (single inheritance).

A subclass inherits all the members (fields, methods, and nested classes)
from its superclass.

Constructors are not members, so they are not inherited by subclasses.


But the constructor of the superclass can be invoked from the subclass.
11

Tuesday, July 31, 12


The Java platform class hierarchy

java.lang.Object is the
base class of all Java
objects.

Classes near the bottom


of the hierarchy provide
more specialized
behavior.

12

Tuesday, July 31, 12


An example of inheritance
class MountainBike extends Bicycle {

// new fields and methods defining


// a mountain bike would go here

MountainBike has the same fields


and methods as Bicycle.

13

Tuesday, July 31, 12


class Bicycle {
The fields represent the
int cadence = 0; objects state.
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


The methods define its interaction
gear = newValue;
} with the outside world.

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:"
+ gear);
}
}
14

Tuesday, July 31, 12


An example of inheritance
public class MountainBike extends Bicycle {
public int seatHeight;

public MountainBike(int startHeight, int startCadence,


int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}

public void setHeight(int newValue) {


seatHeight = newValue;
}
}

15

Tuesday, July 31, 12


Inheritance
A subclass inherits all the public and protected members of its parent, no matter what
the package the subclass is in.

If the subclass is in the same package as its parent, it also inherits the package-private
members of the parent.

If you declare a field in the subclass with the same name as the one in the
superclass --> hide it (not recommended)

If you write a new instance method that has the same signature as the one in the
superclass --> override it.

If you write a new static method that has the same signature as the one in the
superclass --> hide it.

Use the keyword super to invoke the constructor of the superclass.


16

Tuesday, July 31, 12


Private members in a superclass

A subclass does not inherit the private member of its parent class.

However, if the superclass has public or protected methods for


accessing its private fields, they can be used to access these fields.

A nested class has access to all the private members of its enclosing
class--both fields and methods.

Therefore, a public or protected nested class inherited by a subclass


has indirect access to of the private members of the superclass.

17

Tuesday, July 31, 12


Casting objects
The object myBike is of type MountainBike:

MountainBike myBike = new MountainBike();

MountainBike is descended from Bicycle and Object:

A MountainBike is a Bicycle and is also an Object.

Casting shows the use of an object of one type in place of another type.

Object obj = new MountainBike();

Implicit casting: obj is both an Object and a MountainBike.


if (obj instanceof MountainBike) {
Explicit casting: MountainBike myBike = (MountainBike)obj;
} 18

Tuesday, July 31, 12


Overriding and hiding methods
An instance method in a subclass with the same signature and return type
as an instance method in the superclass overrides the superclass method.

This allows a class to inherit from a superclass whose behavior is


similar and then to modify behavior as needed.

Use @override annotation to instruct the compiler (optional).

If a subclass defines a class method with the same signature as a class


method in the superclass, the method in the subclass hides the one in the
superclass.

Note that the access modifier for an overriding method can allow more,
but not less, access than the overridden method.
19

Tuesday, July 31, 12


Overriding and hiding methods
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}

public class Cat extends Animal {


public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
} The class method in Animal.
} The instance method in Cat. 20

Tuesday, July 31, 12


Polymorphism

Subclasses of a class can define their own unique behaviors and yet
share some of the same functionality of the parent class.

Suppose that we have a base class Person and three subclasses


Vietnamese, English and French.
public class Person { class English extends Person {
public void sayHello() { @Override
System.out.print("I will say: "); public void sayHello() {
} super.sayHello();
} System.out.println("Hello!");
}
}
class Vietnamese extends Person {
@Override class French extends Person {
public void sayHello() { @Override
super.sayHello(); public void sayHello() {
System.out.println("Xin cho!"); super.sayHello();
} System.out.println("Bonjour!");
} }
} 21

Tuesday, July 31, 12


Polymorphism
public class TestPerson {
public static void main(String[] args) {
The Java virtual machine calls the
Person p0, p1, p2; appropriate method for the object
p0 = new Vietnamese();
p1 = new English();
that is referred to in each variable.
p2 = new French();
p0.sayHello(); This is virtual method invocation, an
p1.sayHello();
p2.sayHello(); important aspect of polymorphism.
}
}

I will say: Xin cho!


I will say: Hello!
I will say: Bonjour!

22

Tuesday, July 31, 12


Object as a superclass

java.lang.Object is the root class of all the classes.

Some important methods of Object that we may want to inherit:


protected Object clone() throws CloneNotSupportedException;
public boolean equals(Object obj);
protected void finalize() throws Throwable;
public int hashCode();
public String toString();

23

Tuesday, July 31, 12


Writing final classes and methods
You can declare some or all of a classs methods final.

This indicates that the method cannot be overridden by subclasses.

You make a method final if it has an implementation that should not be changed and
is critical to the consistent state of the object.
class ChessAlgorithm {
enum ChessPlayer {WHITE, BLACK}
//...
final ChessPlayer getFirstPlayer() {
return ChessPlayer.WHITE;
}
//...
}
Methods called from constructors should be declared final.

Final classes cannot be subclassed.


24

Tuesday, July 31, 12


Abstract methods and classes
An abstract class is a class declared abstract. It may or may not include
abstract methods.

Abstract method: abstract void moveTo(double deltaX, double deltaY);

If a class includes an abstract method, that class must be abstract:


public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}

If a subclass of an abstract class does not provide implementations for all


abstract methods in its parent class, it has to also be declared abstract.
25

Tuesday, July 31, 12


Abstract class versus interfaces

Unlike interfaces, abstract classes can contain fields that are not static
and final and they can contain implemented methods.

Interfaces: full abstraction

Abstract class: partial abstraction

Abstract classes are most commonly subclassed to share pieces of


implementation.

26

Tuesday, July 31, 12


An abstract class example
In an object-oriented drawing application, you can draw many different
graphic objects.

They all have certain states (position, orientation, line color, fill color...) and
behaviors (moveTo, rotate, resize, draw...).

Some of these states and behaviors are the same for all objects: position,
fill color, moveTo.

Some require different implementations: resize, draw.


27

Tuesday, July 31, 12


An abstract class example
abstract class GraphicObject { class Circle extends GraphicObject {
int x, y; void draw() {
// ... //...
void moveTo(int newX, int newY) { }
//... void resize() {
} //...
abstract void draw(); }
abstract void resize(); }
}
class Rectangle extends GraphicObject {
void draw() {
//...
}
void resize() {
//...
}
}

28

Tuesday, July 31, 12


Reference

The Java Tutorial

Trail: Learning the Java language

http://docs.oracle.com/javase/tutorial/java/TOC.html

29

Tuesday, July 31, 12


Exercise

Exercise 1. Consider the Card, Deck and DisplayDeck classes that you
wrote in a previous exercise (previous lectures).

What Object methods should these classes override?

Override these methods with suitable implementation.

Exercise 2. See the file 04-OOP-Exercises.pdf.

30

Tuesday, July 31, 12