0% found this document useful (0 votes)
0 views49 pages

Advanced Java - 06

This document discusses abstract classes and interfaces in Java, highlighting their roles in defining common behaviors and enabling polymorphism. It explains the structure and usage of abstract classes, including their methods and instantiation rules, as well as the definition and implementation of interfaces. The document also compares abstract classes and interfaces, providing guidelines on when to use each in programming design.
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)
0 views49 pages

Advanced Java - 06

This document discusses abstract classes and interfaces in Java, highlighting their roles in defining common behaviors and enabling polymorphism. It explains the structure and usage of abstract classes, including their methods and instantiation rules, as well as the definition and implementation of interfaces. The document also compares abstract classes and interfaces, providing guidelines on when to use each in programming design.
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/ 49

Java Programming

Chapter 6

Abstract Classes and


Interfaces

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Motivations
• If you want to write a simple program to create and
display G U I components. Can you write the code to
respond to user actions, such as clicking a button to
perform an action?
• In order to write such code, you have to know about
interfaces. A superclass defines common behavior for
related subclasses. An interface can be used to define
common behavior for classes (including unrelated
classes). Before discussing interfaces, we introduce a
closely related subject: abstract classes.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Objectives (1 of 2)
13.1 To design and use abstract classes (§13.2).
13.2 To generalize numeric wrapper classes, BigInteger, and BigDecimal
using the abstract Number class (§13.3).

13.4 To specify common behavior for objects using interfaces (§13.5).

13.5 To define interfaces and define classes that implement interfaces (§13.5).

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Abstract Classes and Abstract Methods

• Consider the following class hierarchy

Shape

Circle Square

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Problem AND Requirements
• Suppose that in order to exploit polymorphism, we specify that 2-D
objects must be able to compute their area.

• All 2-D classes must respond to area() message.

• How do we ensure that?


• Define area method in class Shape
• Force the subclasses of Shape to respond area() message

• Java’s Solutions
• Abstract Classes
• Interfaces

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Abstract Classes
• Idea
• To define only part of an implementation
Can contain instance methods that are fully
implemented
• Leaving the subclasses to provide the details
• Any class with an abstract method must be declared
abstract
However you can declare a class abstract that has
no abstract method.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Abstract Classes
• If subclass overrides all abstract methods of the
superclass, than it becomes a concrete class
otherwise we have to declare it as abstract or we
can not compile it
• Any subclass can override a concrete method inherited
from the superclass and declare them abstract

• However references to an abstract class can be


declared ,Can point to the objects of concrete
subclasses

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Abstract Classes and Abstract Methods

GeometricObject

Circle

Rectangle

TestGeometricObject

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Abstract Method in Abstract Class
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. In other words, in a nonabstract subclass
extended from an abstract class, all the abstract methods
must be implemented, even if they are not used in the
subclass.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Object Cannot Be Created From Abstract
Class
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.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


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.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


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.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


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[] geo = new GeometricObject[10];

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Check point
• Which of the following classes defines a legal abstract
class?

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Case Study: The Abstract Number Class

LargestNumbers

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interfaces
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


What Is an Interface? Why Is an Interface
Useful?

An interface is a classlike construct that contains only


constants and abstract methods. In many ways, an
interface is similar to an abstract class, but the intent of an
interface is to specify common behavior for objects. For
example, you can specify that the objects are comparable
using appropriate interfaces.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Define an Interface
To distinguish an interface from a class, Java uses the following syntax
to define an interface:

public interface InterfaceName {


constant declarations;
abstract method signatures;
}

Example:

public interface Edible {


/** Describe how to eat */
public abstract String howToEat();
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interfaces Definition Example

• Syntax (appears like abstract class):


• All methods are abstract and public by default and can not be
altered
• All constants are static and final by default and can not be altered

public interface Speaker {

public void speak( );

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interface Is a Special Class
An interface is treated like a special class in Java. Each
interface is compiled into a separate bytecode file, just like
a regular class. Like an abstract class, you cannot create
an instance from an interface using the new operator, but
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, as the result
of casting, and so on.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Implementing (Using) Interfaces
• Classes Implement interfaces

– Implementing an interface is like signing a contract.

– A class that implements an interface will have to provide the


definition of all the methods that are present inside an interface“

– If the class does not provide definitions of all methods, the class
would not compile. We have to declare it as an abstract class in
order to get it compiled.

• “Responds to” relationship


– Relationship between a class and interface

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interface - Example

<<Interface>>
Speaker
speak()

Politician Coach Lecturer


speak() speak() speak()

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}

class Coach implements Speaker {


public void speak(){
System.out.println(“Sports Talks”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Teaches Advanced Java”);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
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, as shown below:

A constant defined in an interface can be accessed using


syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Check point
• Suppose A is an interface. Can you create an instance
using new A()?
• Suppose A is an interface. Can you declare a reference
variable x with type Alike this? A x;
• Show the error in the following code:

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Example
You can now use the Edible interface 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 (See
TestEdible).

Edible TestEdible
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: The Comparable Interface
// This interface is defined in
// java.lang package
package java.lang;

public interface Comparable<E> {


public int compareTo(E o);
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Integer and BigInteger Classes

String and Date Classes

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Example (2 of 2)
1. System.out.println(new Integer(3).compareTo(new Integer(5)));

2. System.out.println("ABC".compareTo("ABE"));

3. java.util.Date date1 = new java.util.Date(2013, 1, 1);

4. java.util.Date date2 = new java.util.Date(2012, 1, 1);

5. System.out.println(date1.compareTo(date2));

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


More on Interfaces
• Interface imposes a design structure on any class that uses the
interface
• Leaves the implementation details to the implementing class and
hides that implementation from the client.
• A class can implement more than one interfaces. Java’s way of
multiple inheritance
class Circle implements Drawable, Printable {
//additional constants and abstract methods
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


More on Interfaces (cont.)
• Classes inherit from classes (Single), interfaces inherit from
interfaces (Can be multiple) and classes implement interfaces (Can
be multiple)
public interface Displayable extends Drawable, Printable {
//additional constants and abstract methods
}

• Objects of interfaces cannot be instantiated.


Speaker sp = new Speaker(); // not compile

• However a reference of interface can be created to point to any of


its implementation class (Interface based polymorphism).

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interfaces as solution to Multiple
Inheritance
public interface A
• The problem of multiple { default void hello()
inheritance (Diamond Problem)
{ System.out.println(“A”);}
is solved using super keyword. }

public interface B extends A


{
default void hello()
{ System.out.println(“B”);}
A
}
public class C implements A,B
{ public static void main(String args[])
B C
{ new C().hello();}
}
D

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interfaces as solution to Multiple
Inheritance
public class C implements A,B
{
public void hello()
{
A.super.hello();
}
public static void main(String args[])
{ new C().hello();
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interface based Polymorphism

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Review again – Interface Example

<<Interface>>
Speaker
speak()

Politician Coach Lecturer


speak() speak() speak()

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Example: Interface based Polymorphism
/* Speaker interface is implemented by the Politician, Coach and Lecturer class. */

public class Test{

public static void main (String args[ ]) {

Speaker sp = null;

System.out.println("sp pointing to Politician");


sp = new Politician();
sp.speak();

System.out.println("sp pointing to Coach");


sp = new Coach();
sp.speak();

System.out.println("sp pointing to Lecturer");


sp = new Lecturer();
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interface based Polymorphism
Compile & Execute

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interfaces v s Abstract Classes (1 of 2)
ersu

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.
Blank

Variables Constructors Methods


Abstract No restrictions. Constructors are invoked by No restrictions.
class subclasses through constructor
chaining. An abstract class cannot
be instantiated using the new
operator.
Interface All variables must be No constructors. An interface cannot All methods must be
public static final be instantiated using the new public abstract
operator. instance methods

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Interfaces v s Abstract Classes (2 of 2)
ersu

All classes share a single root, the Object class, but there is no single root for
interfaces. Like a class, an interface also defines a type. A variable of an
interface type can reference any instance of the class that implements the
interface. If a class extends an interface, this interface plays the same role as a
superclass. You can use an interface as a data type and cast a variable of an
interface type to its subclass, and vice versa.

Suppose that c is an instance of Class2. c is also an instance of Object, Class1,


Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution: Conflict Interfaces
In rare occasions, a class may implement two interfaces
with conflict information (e.g., two same constants with
different values or two methods with same signature but
different return type). This type of errors will be detected by
the compiler.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Whether to Use an Interface or a Class?
Abstract classes and interfaces can both be used to model
common features. How do you decide whether to use an
interface or a class? In general, a strong is-a relationship that
clearly describes a parent-child relationship should be modeled
using classes. For example, a staff member is a person. A weak
is-a relationship, also known as an is-kind-of relationship,
indicates that an object possesses a certain property. A weak is-
a relationship can be modeled using interfaces. For example, all
strings are comparable, so the String class implements the
Comparable interface. You can also use interfaces to circumvent
single inheritance restriction if multiple inheritance is desired. In
the case of multiple inheritance, you have to design one as a
superclass, and others as interface.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Designing a Class (1 of 4)
(Coherence) A class should describe a single entity, and all
the class operations should logically fit together to support
a coherent purpose. You can use a class for students, for
example, but you should not combine students and staff in
the same class, because students and staff have different
entities.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Designing a Class (2 of 4)
Classes are designed for reuse. Users can incorporate
classes in many different combinations, orders, and
environments. Therefore, you should design a class that
imposes no restrictions on what or when the user can do
with it, design the properties to ensure that the user can set
properties in any order, with any combination of values,
and design methods to function independently of their
order of occurrence.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Designing a Class (3 of 4)
Provide a public no-arg constructor and override the some
methods defined in the Object class whenever possible.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Designing a Class (4 of 4)
Follow standard Java programming style and naming
conventions. Choose informative names for classes, data
fields, and methods. Always place the data declaration
before the constructor, and place constructors before
methods. Always provide a constructor and initialize
variables to avoid programming errors.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Using Visibility Modifiers (1 of 2)
Each class can present two contracts – one for the users of
the class and one for the extenders of the class. Make the
fields private and accessor methods public if they are
intended for the users of the class. Make the fields or
method protected if they are intended for extenders of the
class. The contract for the extenders encompasses the
contract for the users. The extended class may increase
the visibility of an instance method from protected to public,
or change its implementation, but you should never change
the implementation in a way that violates that contract.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Using Visibility Modifiers (2 of 2)
A class should use the private modifier to hide its data from
direct access by clients. You can use get methods and set
methods to provide users with access to the private data,
but only to private data you want the user to see or to
modify. A class should also hide methods not intended for
client use.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Using the Static Modifier
A property that is shared by all the instances of the class
should be declared as a static property.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Copyright

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved

You might also like