Week 3 Power Point Slides

advertisement

POLYMORPHISM

Definition: Accessing child class methods through a parent object

Example: Child class overrides default parent class methods

Example: Child class fills in methods left blank in the parent’s class

Reserved Words

 implements, interface: Multiple-inheritance

 abstract: Class with some methods left blank

INHERITANCE

Inheritance allows

Programs to make use of parent class methods

A degree of polymorphism when the parent class has a default version of a method to be overridden

Limitations

Programs can only extend a single class

There is no accounting for methods for which there is not a version in the parent class

Note: Java’s use of inheritance providing limited polymorphism is not universal. C++, for example, always calls parent class methods, even if they are overridden.

DESIGN ISSUES

When there are multiple levels of inheritance

The classes at the top of the hierarchy are more and more general

Child classes become more specific to the application

Issues to address

Anticipating methods that all child classes must include

(reserved word abstract )

Providing categories of methods that classes of a particular category must include (reserved words interface and implements)

UML EXAMPLE

Object

GeoMetric Object

-color: Color

-filled: boolean

+getColor(): Color

+setColor(color: Color): void

+isFilled(): boolean

+ findArea(): double

+ findPerimeter(): double

-private, + public, # protected

-How does GeometricObject code findArea and findPerimeter

Circle

-radius: double

+getRadius(): double

+setRadius(radius: double): void

-height: double

Cylinder

+getHeight(): double

+setHeight(height: double): void

+findVolume(): double

Rectangle

-width: double

-height: double

+getWidth(): double

+setWidth(width: double): void

+getHeight(): double

+setHeight(double: height): void

ABSTRACT CLASSES

Definition: Some methods are left to implement in child classes

Note: Parent abstract classes, with empty methods, can’t be instantiated public abstract class GeometricObject

{ private Color color; protected GeometricObject() {} protected GeometricObject(Color color) { this.color = color; } public String getColor()() { return color; } public void setColor(String color) { this.color = color; } public boolean isFilled() { return color==null; } public abstract double findArea(); public abstract double findPerimeter();

CHILD CLASSES OF ABSTRACT PARENTS

In Circle public double findArea() { return radius * radius * Math.PI; } public double findPerimeter( return 2 * radius * Math.PI; }

In Rectangle public double findArea() { return width * height; } public double findPerimeter( 2 * (width + height); }

In Cylinder public double findArea()

{ return 2 * (super.findArea() + getRadius() * Math.PI * height; } public double findVolume() { return super.findArea() * height; }

ABSTRACT CLASS RULES

Any class with abstract methods must also be declared to be abstract

A class with no abstract methods can be declared to be abstract

Any class declared abstract cannot be instantiated

A child class of a concrete (not abstract) parent can be declared abstract

Consider: abstract class Test {}

Legal: Test test;

Illegal: Test test1 = new Test();

INTERFACE

Definition: A class-like construct consisting of constants and method signatures

Syntax:

} modifier interface interfaceName

{ *** constant declarations ***

*** method signatures ***

Usage: public class myClass implements interface1, … , interfaceN

INTERFACE MODIFIERS

Most interfaces are public

Illegal private interface Foo{ } protected interface Bar{ }

}

Legal public class Enclosing

{ private interface Foo{ } protected interface Bar{ }

Interface member scope

 variables are public final static methods are public

Note: public interface T

{ public static final int x=1; public abstract void p();

}

Is equivalent to:

} public interface T

{ int x = 1; void p();

INTERFACE VERSES ABSTRACT

 abstract class advantages over interfaces

 abstract classes can have methods with bodies

 abstract classes can have non-constant variables abstract classes allows protected, private scope

Abstract classes inherit from the Object class

Interface advantages over abstract classes

A class can implement more than one interface

An interface can extend more than one parent interface

Interfaces do not inherit from a root Object

Both abstract classes and interfaces allow

Interface or abstract class names are valid types

TYPE DECLARATION EXAMPLE

public class S extends P

{ public static void main(String[] args)

{ S s = new S();

P p;

Q q;

R r; p = s; q = s; r = s;

} } interface Q {} interface R {} abstract class P implements Q, R {}

IMPLEMENTS AND EXTENDS EXAMPLE

face2 face1 face3 face5 face4

Object Class1

Class2 public class Class2 extends Class1 implements face4, face5 {} abstract class Class1 implements face3 {} interface face1 {} interface face2 {} interface face3 extends face1, face2 {} interface face4 extends face3 {} interface face5 {}

CUSTOM INTERFACE

Output

Nuggets

Apple Cider public class TestEdible

{ public static void main(String[] args)

{ Object[] objs = {new Tiger(), new Chick(), new Apple() }; for (int i=0; i<objs.length; i++) if (objs[i] instanceof Eat) System.out.println(((Eat)objs[i]).how());

} } interface Eat { public String how(); } class Fruit implements Eat {public String how() { return "Eat Fresh";} } class Apple extends Fruit { public String how() { return "Apple Cider"; } } abstract class Animal {} class Tiger extends Animal {} class Chick extends Animal implements Eat

{ public String how() { return "Nuggets"; } }

JAVA COMPARABLE INTERFACE

package java.lang; public interface Comparable { public int compareTo(Object o); } public class Max

{ public static Object max(Object o1, Object o2)

{ if (((Comparable)o1).compareTo(o2) > 0) return o1; else return o2; } }

} public class CompareRect extends Rectangle implements comparable

{ public CompareRect(double width, double height) { super(width, height); } public int compareTo(Object o)

{ return findArea() - ((CompareRect)o).findArea()); }

JAVA “SHALLOW” CLONEABLE INTERFACE

}

{ public class House implements Cloneable public GregorianCalendar built;

} public House(GregorianCalendar b) { built=b; } public Object clone()

{ try { return super.clone(); } catch (CloneNotSupportedException ex) { return null; }

} public static void main(String[] args)

{ House h1 = new House( new GregorianCalendar(35, 11, 10) );

House h2 = (House)h1.clone(); h2.built.set(50, 2, 20);

System.out.println( h1.built.get(Calendar.YEAR) + " " + h2.built.get(Calendar.YEAR));

Output: 50 50 because addresses, not contents , of built copied

JAVA “DEEP” CLONEABLE INTERFACE

Modify the cloneable method from the previous slide

} public Object clone()

{ try

{ House house = (House)super.clone(); house.built = new GregorianCalendar( built.get(Calendar.YEAR), built.get(Calendar.MONTH), built.get(Calendar.DAY_OF_MONTH)); return house;

} catch (CloneNotSupportedException ex) { return null; }

Output: 35 50 because we cloned the instance variable

Alternative : house.built = (GregorianCalendar)built.clone();

Many Java API classes implement “deep” clone operations

WRAPPER CLASSES

Definition: A class that adds functionality to a primitive variable or another class

Examples: Double, Float, Long, Integer, Short, Byte,

Character, Boolean

Additional functionality:

Implements Comparable for Java’s generic sort capabilities

Parses strings into primitive types (Integer.parseInt("32");

Java’s default conversions to and from primitive variables.

int x = Integer.parseInt("1A", 16); sets x to 26

Integer intObject = 2;

BOXING AND UN-BOXING

Definition: Automatic conversion from a primitive variable to its wrapper

Definition: Un-boxing is the automatic conversion from a wrapper object to its primitive variable counterpart

Examples:

Integer x = 3; // Boxing

 int x = Integer(3); // Unboxing

 double d = Double.valueOf(“93.55”); // Unboxing

String h = (Double.valueOf("23.4")).toString();

(The toString method of Double is called)

WRAPPER CLASS UML EXAMPLE

Java.lang.Number

+byteValue(): byte

+shortValue(): short

+intValue(): int

+longValue(): long

+floatValue(): float

+doubleValue(): double

Java.lang.Integer

-value: int

+MAX_VALUE: int

+MIN_VALUE: int

+Integer(vallue: int)

+Integer(s: String)

+valueOf(s: String): Integer

+valueOf(s: String, radix:int): Ingeter

+parseInt(s: String): int

+parseInt(s: String, radix: int): int

Java.lang.Comparable

+compareTo(o: Object): int

Download