Abstract Class Interfaces
Abstract Class Interfaces
Interfaces
Object-Oriented Programming
Contents
Abstract Classes and Abstract Methods
The abstract Calendar class and its GregorianCalendar subclass
Interfaces
Define an Interface
Omitting Modifiers in Interfaces
The Comparable Interface
Writing a generic max Method
The Cloneable Interface
Shallow vs. Deep Copy
Interfaces vs. Abstract Classes
Conflicting interfaces
Wrapper Classes: The Number Class and subclasses
BigInteger and BigDecimal
2
The Rational Class
Abstract Classes and Abstract Methods
GeometricObject Abstract classes
-color: String are italicized or
have the
-filled: boolean annotation
-dateCreated: java.util.Date <abstract>
The # sign indicates
protected modifier #GeometricObject()
#GeometricObject(color: string,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
Abstract methods +getArea(): double
are italicized or +getPerimeter(): double Methods getArea and getPerimeter are overridden in
have the Circle and Rectangle. Superclass abstract methods are
annotation generally omitted in the UML diagram for subclasses.
<abstract>
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: string, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double,
+getRadius(): double color: string, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getDiameter(): double +setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
3
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
protected GeometricObject() {
dateCreated = new java.util.Date();
}
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public boolean isFilled() { return filled; }
public void setFilled(boolean filled) { this.filled = filled; }
public java.util.Date getDateCreated() { return dateCreated; }
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
/** Abstract method getArea */
public abstract double getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();
}
public class Circle extends GeometricObject {
private double radius;
public Circle() { }
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return radius * radius * Math.PI;
}
public double getPerimeter() {
return 2 * radius * Math.PI;
}
public double getDiameter() {
return 2 * radius;
}
}
public class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle() {
// super();
}
public Rectangle(double width, double height) {
this();
this.width = width;
this.height = height;
}
public Rectangle(double width, double height, String color,
boolean filled) {
super(color,filled);
this.width = width;
this.height = height;
}
public double getWidth() { return width; }
public void setWidth(double width) { this.width = width; }
public double getHeight() { return height; }
public void setHeight(double height) { this.height = height; }
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
public class TestGeometricObject1 {
public static void main(String[] args) {
// Declare and initialize two geometric objects
GeometricObject geoObject1 = new Circle(5);
GeometricObject geoObject2 = new Rectangle(5, 3);
// Display circle
displayGeometricObject(geoObject1);
// Display rectangle
displayGeometricObject(geoObject2);
System.out.println("The two objects have the same area? " +
equalArea(geoObject1, geoObject2));
}
8
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
subclasses of abstract classes
In a nonabstract (a.k.a., concrete) subclass extended from
an abstract super-class, all the abstract methods MUST be
implemented.
abstract class A {
abstract void m();
}
class B extends A {
void m(){
}
}
9
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
subclasses of abstract classes
In an abstract subclass extended from an abstract
super-class, we can choose:
to implement the inherited abstract methods OR
to postpone the constraint to implement the
abstract methods to its nonabstract subclasses.
10
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract class A {
abstract void m();
}
class C extends B {
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract class A{
abstract void m();
}
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract classes
A subclass can be abstract even if its
superclass is concrete.
For example, the Object class is concrete, but
a subclass, GeometricObject, is abstract
13
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract classes
A subclass can override a method
from its concrete superclass to
define it abstract
useful when we want to force
its subclasses to implement that
method, or
the implementation of the
method in the superclass is
invalid in the subclass
14
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract classes
It is possible to define an abstract class that contains no
abstract methods.
This class is used as a base class for defining new
subclasses.
15
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract classes
An object cannot be created from abstract class:
An abstract class cannot be instantiated using the new
operator:
GeometricObject o =
new GeometricObject();
We still define its constructors, which are invoked in the
constructors of its subclasses through constructor
chaining.
For instance, the constructors of GeometricObject are
invoked by the constructors in the Circle and the
16
Rectangle classes.
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
abstract classes as types
An abstract class can be used as a data type:
GeometricObject c = new Circle(2);
We can create an array whose elements are of
GeometricObject type:
GeometricObject[] geo =
new GeometricObject[10];
There are only null elements in the array until they are
initialized with concrete objects:
geo[0] = new Circle();
geo[1] = new Rectangle();
…
17
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The abstract Calendar class and its
GregorianCalendar subclass
An instance of java.util.Date represents a specific
instant in time with millisecond precision
java.util.Calendar is an abstract base class for
extracting detailed information such as year, month, date,
hour, minute and second from a Date object for a specific
calendar
Subclasses of Calendar can implement specific calendar
systems such as Gregorian calendar, Lunar Calendar and Jewish
calendar.
java.util.GregorianCalendar is for the modern
Gregorian calendar
18
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The GregorianCalendar Class
Java API for the GregorianCalendar class:
http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html
new GregorianCalendar() constructs a default
GregorianCalendar with the current time
new GregorianCalendar(year, month,
date) constructs a GregorianCalendar with the
specified year, month, and date
The month parameter is 0-based, i.e., 0 is for January, 1
is for February, …, 11 is for December.
19
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The abstract Calendar class and its
GregorianCalendar subclass
java.util.Calendar
#Calendar() Constructs a default calendar.
+get(field: int): int Returns the value of the given calendar field.
+set(field: int, value: int): void Sets the given calendar to the specified value.
+set(year: int, month: int, Sets the calendar with the specified year, month, and date. The month
dayOfMonth: int): void parameter is 0-based, that is, 0 is for January.
+getActualMaximum(field: int): int Returns the maximum value that the specified calendar field could have.
+add(field: int, amount: int): void Adds or subtracts the specified amount of time to the given calendar field.
+getTime(): java.util.Date Returns a Date object representing this calendar’s time value (million
second offset from the Unix epoch).
+setTime(date: java.util.Date): void Sets this calendar’s time with the given Date object.
java.util.GregorianCalendar
+GregorianCalendar() Constructs a GregorianCalendar for the current time.
+GregorianCalendar(year: int, Constructs a GregorianCalendar for the specified year, month, and day of
month: int, dayOfMonth: int) month.
+GregorianCalendar(year: int, Constructs a GregorianCalendar for the specified year, month, day of
month: int, dayOfMonth: int, month, hour, minute, and second. The month parameter is 0-based, that
hour:int, minute: int, second: int) is, 0 is for January.
20
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The get Method in the Calendar Class
The get(int field) method defined in the Calendar class is useful to extract
the date and time information from a Calendar object.
The fields are defined as constants in Calendar, as shown in the following:
Constant Description
24
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Interface Example
The Edible interface specifies whether an object is edible
public interface Edible {
public abstract String howToEat();
}
The class Chicken implements the Edible interface:
class Chicken extends Animal implements Edible {
public String howToEat() {
return "Chicken: Fry it";
}
}
25
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
interface Edible {
public abstract String howToEat(); /** Describe how to eat */
}
abstract class Animal { }
class Chicken extends Animal implements Edible {
public String howToEat() {
return "Chicken: Fry it";
}
}
class Tiger extends Animal {
}/** Does not extend Edible */
abstract class Fruit implements Edible { }
class Apple extends Fruit {
public String howToEat() {
return "Apple: Make apple cider";
}
}
class Orange extends Fruit {
public String howToEat() {
return "Orange: Make orange juice";
}
}
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (Object o:objects)
if (o instanceof Edible)
System.out.println(((Edible)o).howToEat());
}
} (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Omitting Modifiers in Interfaces
In an interface:
All data fields are public static final
All methods are public abstract
These modifiers can be omitted:
public interface T1 { public interface T1 {
public static final int K = 1; Equivalent int K = 1;
27
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Interfaces
An interface is treated like a special class in Java:
Each interface is compiled into a separate
bytecode (.class) file just like a regular class.
Like an abstract class, you cannot create an
instance from an interface using the new operator
Uses of interfaces are like for abstract classes:
as a data type for a variable
as the result of casting
28
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The Comparable Interface
The Comparable interface is defined in the
java.lang package and it is used by
Arrays.sort
package java.lang;
public interface Comparable {
int compareTo(Object o);
}
29
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The Comparable Interface
Many classes in the Java library implement
Comparable (e.g., String and Date) to
define a natural order for the objects:
public class String extends Object public class Date extends Object
implements Comparable { implements Comparable {
// class body omitted // class body omitted
} }
30
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Object «interface» In UML, the interface and
- java.lang.Comparable the methods are italicized
+compareTo(o: Object): int
dashed lines and triangles
are used to point to the
interface
String
31
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Writing a generic max Method
// Max.java: Find a maximum object // Max.java: Find a maximum object
public class Max { public class Max {
/** Return the maximum of two objects */ /** Return the maximum of two objects */
public static Comparable max public static Object max
(Comparable o1, Comparable o2) { (Object o1, Object o2) {
if (o1.compareTo(o2) > 0) if (((Comparable)o1).compareTo(o2) > 0)
return o1; return o1;
else else
return o2; return o2;
} }
} }
(a) (b)
The return value from the max method is of the Comparable type. So,
we need to cast it to String or Date explicitly.
32
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Defining Classes to Implement Comparable
We cannot use the max method to find the larger of two instances
of Rectangle, because Rectangle does not implement Comparable
We can define a new rectangle class ComparableRectangle that
implements Comparable: the instances of this new class are
comparable
GeometricObject «interface»
- java.lang.Comparable
ComparableRectangle
33 - (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
public class ComparableRectangle extends Rectangle
implements Comparable {
/** Construct a ComparableRectangle with specified properties */
public ComparableRectangle(double width, double height) {
super(width, height);
}
35
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Sorting an Array of Objects
public class GenericSort {
public static void main(String[] args) {
Integer[] intArray={new Integer(2),new Integer(4),new Integer(3)};
sort(intArray); // or Arrays.sort(intArray);
printList(intArray);
The objects are instances of the
}
Comparable interface and they are
public static void sort(Object[] list) {
compared using the compareTo
Object currentMax;
method.
int currentMaxIndex;
for (int i = list.length - 1; i >= 1; i--) {
currentMax = list[i];
currentMaxIndex = i; // Find the maximum in the list[0..i]
for (int j = i - 1; j >= 0; j--) {
if (((Comparable)currentMax).compareTo(list[j]) < 0) {
currentMax = list[j];
currentMaxIndex = j;
}
}
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
public static void printList(Object[] list) {
36 for (int i=0;i<list.length;i++) System.out.print(list[i]+" ");}}
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The Cloneable Interface
Marker Interface: is an empty interface (does not contain
constants or methods), but it is used to denote that a class
possesses certain desirable properties to the compiler and the
JVM.
package java.lang;
public interface Cloneable {
}
A class that implements the Cloneable interface is marked
cloneable:
its objects can be cloned using the clone() method defined in the
Object class, and we can override this method in our classes
37
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The Cloneable Interface
Calendar (in the Java library) implements Cloneable:
Calendar calendar = new GregorianCalendar(2022, 1, 1);
Calendar calendarCopy = (Calendar)(calendar.clone());
System.out.println("calendar == calendarCopy is "
+(calendar == calendarCopy));
Displays:
calendar == calendarCopy is false
because the references are different
System.out.println("calendar.equals(calendarCopy) is"
+ calendar.equals(calendarCopy));
calendar.equals(calendarCopy) is true
because the calendarCopy is a copy of calendar
38
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Implementing the Cloneable Interface
If we try to create a clone of an object instance of a class
that does not implement the Cloneable interface, it
throws CloneNotSupportedException
The clone() method in the Object class creates a new
instance of the class of this object and initializes all its fields with
exactly the contents of the corresponding fields of this object, as if
by assignment (using a technique named reflection); the contents
of the reference data fields are not cloned.
The clone() method returns an Object that needs to be
casted
We can override the clone() method from the Object
class to create custom clones
39
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
public class SomethingCloneable implements Cloneable {
public boolean equals(Object o){
return true;
}
public static void main(String[] args)
throws CloneNotSupportedException {
SomethingCloneable s1 = new SomethingCloneable();
SomethingCloneable s2 = (SomethingCloneable) s1.clone();
System.out.println("s1 == s2 is " + (s1 == s2));
// false
System.out.println("s1.equals(s2) is " + s1.equals(s2));
// true
}
}
40
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
public class House implements Cloneable, Comparable {
private int id;
private double area;
private java.util.Date whenBuilt;
public House(int id, double area) {this.id = id; this.area = area;
whenBuilt = new java.util.Date();}
public double getId() { return id;}
public double getArea() { return area;}
public java.util.Date getWhenBuilt() { return whenBuilt;}
/** Override the protected clone method defined in the Object
class, and strengthen its accessibility */
public Object clone() {
try {
return super.clone();
}catch (CloneNotSupportedException ex) {
return null;
}
}
/** Implement the compareTo method defined in Comparable */
public int compareTo(Object o) {
if (area > ((House)o).area)
return 1;
else if (area < ((House)o).area)
return -1;
else
return 0;
41 } (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
}
Shallow vs. Deep Copy
House house1 = new House(1, 1750.50);
House house2 = (House)(house1.clone());
house1
house1: House Memory
id = 1 1
area = 1750.50 1750.50
whenBuilt reference whenBuilt: Date
44
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Interfaces vs. Abstract Classes
In an interface, the data fields must be constants; an abstract class
can have variable data fields
Interfaces don't have constructors; all abstract classes have
constructors
Each method in an interface has only a signature without
implementation (i.e., only abstract methods); an abstract class can
have concrete methods
Variables Constructors Methods
45
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Inheritance: Interfaces & Classes
An interface can extend any number of other
interfaces
There is no root for interfaces
A class can implement any number of interfaces
Interface1_2 Interface2_2
47
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Whether to use a class or an interface?
Strong is-a: a relationship that clearly describes a parent-
child relationship
For example: a student is a person
Should be modeled using class inheritance
Weak is-a (or is-kind-of): indicates that an object possesses
a certain property
For example: all strings are comparable, all dates are
comparable
Should be modeled using interfaces
You can also use interfaces to circumvent single inheritance
restriction if multiple inheritance is desired
48
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Wrapper Classes
Primitive data types in Java ➔ Better performance
However, data structures (ArrayList) expect objects as elements
Each primitive type has a wrapper class: Boolean, Character, Short,
Byte, Integer, Long, Float, Double
java.lang.Comparable java.lang.Object
- -
+Double(value: double)
+Double(s: String)
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double
+parseDouble(s: String): double
+parseDouble (s: String, radix: int): double
52
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Wrapper Classes
You can construct a wrapper object either from a
primitive data type value or from a string representing the
numeric value
The constructors for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
53
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE:
MAX_VALUE represents the maximum value of the
corresponding primitive data type
For Float and Double, MIN_VALUE represents the
minimum positive float and double values
The maximum integer: 2,147,483,647
55
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Wrapper Classes
Automatic Conversion Between Primitive Types and Wrapper Class Types:
Since JDK 1.5, Java allows primitive type and wrapper classes to be
converted automatically:
boxing of primitive types into wrapper types when objects are needed
Unboxing
56
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Arrays are objects
Arrays are objects:
An array is an instance of the Object class
new int[10] instanceof Object true
If A is a subclass of B, every instance of A[] is an instance of B[]
new GregorianCalendar[10] instanceof Calendar[] true
new Calendar[10] instanceof Object[] true
new Calendar[10] instanceof Object true
Although an int value can be assigned to a double type variable,
int[] and double[] are two incompatible types because they are
not classes:
We cannot assign an int[] array to a variable of double[]
array: compiler error: double[] a = new int[10];
57
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
BigInteger and BigDecimal
BigInteger and BigDecimal classes in the
java.math package:
For computing with very large integers or high precision
floating-point values
BigInteger can represent an integer of any size
BigDecimal has no limit for the precision (as long as
it’s finite=terminates)
Both are immutable
Both extend the Number class and implement the
Comparable interface.
58
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
18446744073709551614
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
0.33333333333333333334
59
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
BigInteger and BigDecimal
import java.math.*;
public class LargeFactorial {
public static void main(String[] args) {
System.out.println("50! is \n" + factorial(50));
}
public static BigInteger factorial(long n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i+""));
return result;
}
} 30414093201713378043612608166064768844377641
568960512000000000000
60
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Case Study: The Rational Class
1
java.lang.Number Rational
+byteValue(): byte -numerator: long
+shortValue(): short -denominator: long
+intValue(): int
+longVlaue(): long +Rational()
+floatValue(): float +Rational(numerator: long, denominator: long)
+doubleValue():double +getNumerator(): long
+getDenominator(): long
+add(secondRational: Rational): Rational
+multiply(secondRational: Rational): Rational
+subtract(secondRational: Rational): Rational
java.lang.Comparable +divide(secondRational: Rational): Rational
+toString(): String
compareTo(Object): int -gcd(n: long, d: long): long
61
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
public class Rational extends Number implements Comparable {
private long numerator = 0;
private long denominator = 1;
public Rational() { this(0, 1); }
public Rational(long numerator, long denominator) {
long gcd = gcd(numerator, denominator);
this.numerator = ((denominator > 0) ? 1 : -1) * numerator / gcd;
this.denominator = Math.abs(denominator) / gcd;
}
private static long gcd(long n, long d) {
long n1 = Math.abs(n);
long n2 = Math.abs(d);
int gcd = 1;
for (int k = 1; k <= n1 && k <= n2; k++) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
}
return gcd;
}
public Rational add(Rational secondRational) {
long n = numerator * secondRational.getDenominator() +
denominator * secondRational.getNumerator();
long d = denominator * secondRational.getDenominator();
return new Rational(n, d);
}
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
public Rational subtract(Rational secondRational) {
… // or implement inverse and use add method
}
// multiply, divide
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)