0% found this document useful (0 votes)
14 views32 pages

Lecture 6

The document is a lecture on Object-Oriented Programming with Java, focusing on abstract classes and interfaces. It explains the concepts of abstract classes, abstract methods, and the Comparable interface, along with examples and code snippets. It also discusses the differences between interfaces and abstract classes, and includes an assignment to design a Triangle class extending an abstract class.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views32 pages

Lecture 6

The document is a lecture on Object-Oriented Programming with Java, focusing on abstract classes and interfaces. It explains the concepts of abstract classes, abstract methods, and the Comparable interface, along with examples and code snippets. It also discusses the differences between interfaces and abstract classes, and includes an assignment to design a Triangle class extending an abstract class.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Object Oriented

Programming
with Java II

Dr. Mohamed K. Hussein


Lecture 6

Associate Prof., Computer Science department,

Faculty of Computers & Information Science,

Suez Canal University

Email: m_khamis@ci.suez.edu.eg
Lecture outcomes
• Abstract Classes
• Abstract class & abstract method

• Interfaces
• The Comparable Interface

• Interface vs. Abstract Classes

Dr. Mohamed K. Hussein 2


Abstract Classes
• An abstract class can contain abstract methods, which are implemented in concrete subclasses.

• An abstract class cannot be used to create objects.

• In the inheritance hierarchy,

• Classes become more specific and concrete with each new subclass.

• If you move from a subclass back up to a superclass, the classes become more general and less

specific.

• Class design should ensure that a superclass contains common features of its subclasses.

• A superclass is so abstract that it cannot be used to create any specific instances.

• Such a class is referred to as an abstract class.


Dr. Mohamed K. Hussein 3
Abstract
Classes
&
Abstract
Methods

Dr. Mohamed K. Hussein 4


Abstract Classes & Abstract Methods
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;

............

/** Abstract method getArea */


public abstract double getArea();

/** Abstract method getPerimeter */


public abstract double getPerimeter();
} Dr. Mohamed K. Hussein 5
Abstract Classes & Abstract Methods

• An abstract method cannot be contained in a nonabstract class.

• If a subclass of an abstract superclass does not implement all the

abstract methods, the subclass must be defined abstract.

• A nonabstract subclass extended from an abstract class, all the abstract

methods must be implemented, even if they are not used in the

subclass.
Dr. Mohamed K. Hussein 6
Abstract Classes

• An abstract class cannot be instantiated using the new operator,


• but you can still define its constructors, which are invoked in the
constructors of its subclasses.
• For instance, the constructors of GeometricObject are invoked in the Circle class
and the Rectangle class.

Dr. Mohamed K. Hussein 7


Example
public class TestClass {
public static void main(String[] args) {
// Create two geometric objects
GeometricObject Object1 = new Circle(5);
GeometricObject Object2 = new Rectangle(5, 3);
// Display objects
displayGeometricObject(Object1);
displayGeometricObject(Object2);
}

/** A method for displaying a geometric object */


public static void displayGeometricObject(GeometricObject object) {
System.out.println();
System.out.println("The area is " + object.getArea());
System.out.println("The perimeter is " + object.getPerimeter());
}
} Dr. Mohamed K. Hussein 8
Abstract class without abstract method

• A class that contains abstract methods must be abstract.

• However, it is possible to define an abstract class that contains no


abstract methods.
• In this case, you cannot create instances of the class using the new operator.

• This class is used as a base class for defining a new subclass.

Dr. Mohamed K. Hussein 9


superclass of abstract class may be concrete

• A subclass can be abstract even if its superclass is concrete.


• For example, the Object class is concrete, but its subclasses, such as
GeometricObject, may be abstract.

Dr. Mohamed K. Hussein 10


concrete method overridden to be abstract

• A subclass can override a method from its superclass to define


it abstract.

• This is rare, but useful when the implementation of the method in the
superclass becomes invalid in the subclass.

• In this case, the subclass must be defined abstract.

Dr. Mohamed K. Hussein 11


abstract class as type
• You cannot create an instance from an abstract class using the new operator,

• But an abstract class can be used as a data type.

• Therefore, the following statement, which creates an array whose elements are of
GeometricObject type, is correct.

GeometricObject[] objects = new GeometricObject[10];

• You can then create an instance of GeometricObject and assign its reference to the array like
this:

objects[0] = new Circle();

Dr. Mohamed K. Hussein 12


Case Study: the Abstract Number Class
• The Number class is an
abstract superclass for
Double, Float, Long, Integer,
Short, Byte, BigInteger and
BigDecimal.

Dr. Mohamed K. Hussein 13


import java.util.ArrayList;
import java.math.*;
public class LargestNumbers { Example
public static void main(String[] args) {
ArrayList<Number> list = new ArrayList<>();
list.add(45); // Add an integer
list.add(3445.53); // Add a double
// Add a BigInteger
list.add(new BigInteger("3432323234344343101"));
// Add a BigDecimal
list.add(new BigDecimal("2.0909090989091343433344343"));
System.out.println("The largest number is " +
getLargestNumber(list));
}
public static Number getLargestNumber(ArrayList<Number> list) {
if (list == null || list.size() == 0)
return null;
Number number = list.get(0);
for (int i = 1; i < list.size(); i++)
if (number.doubleValue() < list.get(i).doubleValue())
number = list.get(i);
return number;
}
Dr. Mohamed K. Hussein 14
}
Interfaces

 What is an interface?

 Why is an interface useful?

 How to define an interface?

 How do you use an interface?

Dr. Mohamed K. Hussein 15


Interfaces
• An interface is containing only constants and Syntax:
abstract methods. Access_modifier interface InterfaceName{

• In many ways, an interface is similar to an /** Constant declarations */


abstract class,
/** Abstract method signatures */
• The intent of an interface is to specify
}
common behavior for objects.
• For example, you can specify that the objects Example:
are comparable, edible, cloneable using public interface Edible {
appropriate interfaces. /** Describe how to eat */
public abstract String howToEat();
Dr. Mohamed K. Hussein
} 16
Interface is a Special Class
• An interface is treated like a special class in Java.

• Like an abstract class, you cannot create an instance from an interface using the
new operator,

• In most cases you can use an interface more or less the same way you use an
abstract class.
• For example, you can use an interface as a data type for a variable.

Dr. Mohamed K. Hussein 17


Example
• The Edible interface is used to
specify whether an object is edible.

• This is accomplished by letting the


class for the object implement this
interface using the implements
keyword.
• For example, the classes Chicken
and Fruit implement the Edible
interface
Dr. Mohamed K. Hussein 18
Example
abstract class Animal {
/** Return animal sound */
abstract class Fruit implements Edible {
public abstract String sound();
// Data fields, constructors, and methods
} omitted here
class Chicken extends Animal implements Edible { }
@Override
public String howToEat() { class Apple extends Fruit {
@Override
return "Chicken: Fry it";
public String howToEat() {
} return "Apple: Make apple cider";
@Override }
public String sound() { }
return "Chicken: AOOAOOO"; class Orange extends Fruit {
@Override
}
public String howToEat() {
} return "Orange: Make orange juice";
class Tiger extends Animal { }
@Override }
public String sound() {
return "Tiger: RROOAARR";
}
} Dr. Mohamed K. Hussein 19
Example
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (int i = 0; i < objects.length; i++) {
if (objects[i] instanceof Edible)
System.out.println(((Edible)objects[i]).howToEat());

if (objects[i] instanceof Animal) {


System.out.println(((Animal)objects[i]).sound());
}
}
}
} Dr. Mohamed K. Hussein 20
Omitting Modifiers in Interfaces

• All data fields are public final static and all methods are public abstract in an

interface.

• For this reason, these modifiers can be omitted

public interface T1 { public interface T1 {


public static final int K = 1; Equivalent int K = 1;

public abstract void p(); void p();


} }

Dr. Mohamed K. Hussein 21


The Comparable Interface
• The Comparable interface defines the
compareTo method for comparing objects.
public interface Comparable<E> {
• The interface is defined in java.lang public int compareTo(E o);
package. }

Dr. Mohamed K. Hussein 22


Integer and BigInteger Classes
public class Integer extends Number public class BigInteger extends Number
implements Comparable<Integer> { implements Comparable<BigInteger> {
// class body omitted // class body omitted

@Override @Override • The compareTo method


public int compareTo(Integer o) { public int compareTo(BigInteger o) {
// Implementation omitted // Implementation omitted determines the order of
} }
} } this object with the
specified object o and
returns a negative integer,
String and Date Classes zero, or a positive integer
public class String extends Object
implements Comparable<String> {
public class Date extends Object
implements Comparable<Date> {
if this object is less than,
// class body omitted // class body omitted
equal to, orgreater than o
@Override @Override
public int compareTo(String o) { public int compareTo(Date o) {
// Implementation omitted // Implementation omitted
} }
} }
Dr. Mohamed K. Hussein 23
The Comparable Interface
• Thus, numbers are comparable, strings are comparable, and so are dates. You can use the
compareTo method to compare two numbers, two strings, and two dates.

• For example, the following code:


System.out.println(new Integer(3).compareTo(new Integer(5)));
System.out.println("ABC".compareTo("ABE"));
java.util.Date date1 = new java.util.Date(2013, 1, 1);
java.util.Date date2 = new java.util.Date(2012, 1, 1);
System.out.println(date1.compareTo(date2));
• Displays
-1
-2
1
Dr. Mohamed K. Hussein 24
Instanceof
• Let n be an Integer object, s be a String object, and d be a Date object.
• All the following expressions are true.

n instanceof Integer s instanceof String d instanceof java.util.Date


n instanceof Object s instanceof Object d instanceof Object
n instanceof Comparable s instanceof Comparable d instanceof Comparable

Dr. Mohamed K. Hussein 25


Generic sort Method
import java.math.*;
public class SortComparableObjects {
public static void main(String[] args) {
String[] cities = {"Savannah", "Boston", "Atlanta", "Tampa"};
java.util.Arrays.sort(cities); The java.util.Arrays.sort
for (String city: cities)
System.out.print(city + " "); (array) method requires
System.out.println();
that the elements in an
BigInteger[] hugeNumbers = {new BigInteger("2323231092923992"),
new BigInteger("432232323239292"),array are instances of
new BigInteger("54623239292")};
java.util.Arrays.sort(hugeNumbers);
Comparable<E>.
for (BigInteger number: hugeNumbers)
System.out.print(number + " ");
}
Dr. Mohamed K. Hussein 26
}
Defining Classes to Implement
Comparable
• You cannot use the sort method to sort an array of Rectangle objects, because Rectangle
does not implement Comparable.
• However, you can define a new rectangle class that implements Comparable.

• The instances of this new class are comparable.

Dr. Mohamed K. Hussein 27


Defining Classes to Implement
Comparable
public class ComparableRectangle extends Rectangle implements Comparable<ComparableRectangle> {
/** Construct a ComparableRectangle with specified properties */
public ComparableRectangle(double width, double height) {
super(width, height);
}
//@Override // Implement the compareTo method defined in Comparable
public int compareTo(ComparableRectangle o) {
if (getArea() > o.getArea())
return 1;
else if (getArea() < o.getArea())
return -1;
else
return 0;
}

//@Override // Implement the toString method in GeometricObject


public String toString() {
return super.toString() + " Area: " + getArea();
}
}` Dr. Mohamed K. Hussein 28
Defining Classes to Implement
Comparable
public class SortRectangles {
public static void main(String[] args) {
ComparableRectangle[] rectangles = {
new ComparableRectangle(3.4, 5.4),
new ComparableRectangle(13.24, 55.4),
new ComparableRectangle(7.4, 35.4),
new ComparableRectangle(1.4, 25.4)};
java.util.Arrays.sort(rectangles);
for (Rectangle rectangle: rectangles) {
System.out.print(rectangle + " ");
System.out.println();
12 }
}
} Dr. Mohamed K. Hussein 29
Interfaces vs. Abstract Classes
• A class can implement multiple interfaces, but it can only extend one superclass.

• In an interface, the data must be constants; an abstract class can have all types of data.

• Each method in an interface has only a signature without implementation; an abstract class can have concrete
methods.

Dr. Mohamed K. Hussein 30


Assignment 6
• Design a Triangle class that extends the abstract GeometricObject class. Draw the UML diagram
for the classes Triangle and GeometricObject and then implement the Triangle class.

• Write a test program that prompts the user to enter three sides of the triangle, a color, and a
Boolean value to indicate whether the triangle is filled.

• The program should create a Triangle object with these sides and set the color and filled
properties using the input.

• The program should display the area, perimeter, color, and true or false to indicate whether it
is filled or not.

• Make the class comparable on the basis of the area.

Dr. Mohamed K. Hussein 31


Thank you

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy