Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Abstrac Class in Java

Page 2

Java Programming

es
2-2

ss
Java Class Design – Abstract Classes

la
C
ct
ra
st
Ab
Abstrac Class in Java
Page 3

Overview

This lesson covers the following topics:

es
• Use Abstract Classes

ss
• Use the instanceof operator to compare object types

la
C
• Use virtual method invocation

ct
• Use upward and downward casts
ra
st
Ab

3
Abstrac Class in Java
Page 4

Abstract Classes

• An abstract class provides a base class from which other

es
classes extend.

ss
• Abstract classes can provide:

la
– Implemented methods: Those that are fully implemented and

C
their child classes may use them.

ct
– Abstract methods: Those that have no implementation and
ra
require child classes to implement them.
st

• Abstract classes do not allow construction directly but you


Ab

can create subclasses or static nested classes to instantiate


them.

4
Abstrac Class in Java
Page 5

Abstract Classes

• An abstract class:

es
– Must be defined by using the abstract keyword.

ss
– Cannot be instantiated into objects.

la
– Can have local declared variables.

C
– Can have method definitions and implementations.

ct
– Must be subclassed rather than implemented.
ra
st
Ab

5
Abstrac Class in Java
Page 6

More Information about Abstract Classes

• If a concrete class uses an abstract class, it must inherit it.

es
Inheritance precludes inheriting from another class.

ss
• Abstract classes are important when all derived classes

la
should share certain methods.

C
• The alternative is to use an interface, then define at least one
ct
concrete class that implements the interface.
ra
st
• This means you can use the concrete class as an object type
Ab

for a variable in any number of programs which provides


much greater flexibility.

6
Abstrac Class in Java
Page 7

Abstract Class or Interface

• There is no golden rule on whether to use Interfaces, Abstract

es
classes or both.

ss
• An abstract class usually has a stronger relationship between

la
itself and the classes that will be derived from it than

C
interfaces.

ct
• Classes and Interfaces can implement multiple interfaces.
ra
Where a class can only be a sub class of one abstract class.
st
Ab

• Abstract classes allow methods to be defined.

7
Abstrac Class in Java
Page 8

Bank Account as Abstract

• Previously we had implemented an interface for the Account

es
class.

ss
public interface InterfaceBankAccount{

la
public final String bank= "JavaBank";
public void deposit(int amt);

C
public void withdraw(int amt);

ct
public int getbalance();
} ra
• We could have used an abstract class instead.
st
Ab

8
Abstrac Class in Java
Page 9

Bank Account as Abstract

• Interface

es
public interface InterfaceBankAccount

ss
{
public final String bank= "JavaBank";

la
public void deposit(int amt);
public void withdraw(int amt);

C
public int getbalance();

ct
}

• Abstract Class
ra
st
public abstract class AbstractBankAccount {
Ab

public final String bank= "JavaBank";


public abstract void deposit(int amt);
public abstract void withdraw(int amt);
public abstract int getbalance();
}

9
Abstrac Class in Java
Page 10

Bank Account as Abstract

• In this implementation there is no advantage of using an

es
abstract class over an interface.

ss
• We would be better using an interface especially if all bank

la
accounts had to implement only those defined methods.

C
• The interface approach would also allows us to use other
ct
interfaces in our class design.
ra
st
• If we wanted some base functionality to be defined then we
Ab

would use an abstract class.


• An example is shown on the following slide.

10
Abstrac Class in Java
Page 11

Bank Account as Abstract


public abstract class AbstractBankAccount {
String accountname;
int accountnum;

es
int balance;
public void deposit(int amt)

ss
{
balance=balance+amt;

la
}
public void withdraw(int amt)

C
{
balance=balance-amt;

ct
}
ra
public void setaccountname(String name)
{
st
accountname = name;
}
Ab

public void setaccountnum(int num)


{
accountnum = num;
}
public abstract int getbalance();
public abstract void print();
}

11
Abstrac Class in Java
Page 12

The instanceof Operator

• The instanceof operator allows you to determine the type of

es
an object.

ss
• It takes an object on the left side of the operator and a type

la
on the right side of the operator and returns a boolean value

C
indicating whether the object belongs to that type or not.
• For example:
ct
ra
– (String instanceof Object) would return true.
st
Ab

– (String instanceof Integer) would return false.

12
Abstrac Class in Java
Page 13

Using the instanceof Operator

• This could be useful when you desire to have different object

es
types call methods specific to their type.

ss
public class CustomerAccounts {

la
private InterfaceBankAccount[] bankaccount = new

C
InterfaceBankAccount[10];
public CustomerAccounts() {

ct
InterfaceBankAccount[] b = {
new Account("Sanjay Gupta",11556,300),
ra
new CreditAccount("Sally Walls",66778,1000,500)
st
};
this.bankaccount = b;
Ab

}
}

13
Abstrac Class in Java
Page 14

instanceof Operator Example

• In this example, the instanceof operator is used to find all of

es
the CreditAccounts in an array and add them to a String

ss
called list.

la
public String getAllCreditAccounts() {

C
String list = "";
for (int i = 0; i < this.bankaccount.length; i++) {

ct
if (this.bankaccount[i] instanceof CreditAccount) {
if (list.length() == 0) {
ra
list += this.bankaccount[i]; }
st
else {
list += ", " + this.bankaccount[i];
Ab

}
}
}
return list;
}

14
Abstrac Class in Java
Page 15

instanceOf Operator Example Explained

• In the previous instanceof operator example:

es
– The array is defined using the InterfaceBankAccount interface. It

ss
can hold any class that solely implements its methods and

la
extends them with other specialization methods and variables.

C
• As the program reads through the array, it assigns the string

ct
value from the toString() method to the list variable.
ra
• You should always consider overridding the toString(), hash(),
st
and equals() methods in your user-defined classes.
Ab

15
Abstrac Class in Java
Page 16

Virtual Method Invocation

• Virtual method invocation is the process where Java identifies

es
the type of subclass and calls its implementation of a method.

ss
• When the Java virtual machine invokes a class method, it

la
selects the method to invoke based on the type of the object

C
reference, which is always known at compile time.

ct
• On the other hand, when the virtual machine invokes an
ra
instance method, it selects the method to invoke based on
st
the actual class of the object, which may only be known at
Ab

runtime.

16
Abstrac Class in Java
Page 17

Virtual Method Invocation Example

es
...
public String toString() {

ss
String list = "";
for (int i = 0; i < this.bankaccount.length; i++) {

la
if (list.length() == 0) {

C
list += this.bankaccount[i]; }
else {

ct
list += "\n : " +this.bankaccount[i];}
} ra
return super.toString() + "\n" + list + "\n"
st
}
...
Ab

Assigning the object to


the String calls that
object's toString
method.

17
Abstrac Class in Java
Page 18

Virtual Method Invocation Example


Explained

es
• The toString() method uses virtual method invocation by

ss
calling the toString() method of the different subclasses.

la
• The decision is made by JVM to call the toString method

C
implemented in the subclasses rather than the toString

ct
method in the superclass or the Object class.
ra
st
Ab

18
Abstrac Class in Java
Page 19

Upcasting and Downcasting

• Casting is the principal of changing the object type during

es
assignment.

ss
• Upcasting loses access to specialized methods in the

la
subclassed object instance.

C
• Downcasting gains access to specialized methods of the
subclass.
ct
ra
st
Ab

19
Abstrac Class in Java
Page 20

Upcasting and Downcasting Example

• Casting objects works somewhat like casting primitives.

es
• For example, when downcasting a double to an int, the values

ss
to the right of the decimal point are lost.

la
• This is a loss of precision.

C
ct
• For that reason, you must explicitly specify the downcast
ra
type.
st
• For example:
Ab

double complexNumber = 45.75L;


int simpleNumber = 34;

simpleNumber = (int) complexNumber;

20
Abstrac Class in Java
Page 21

Upcasting and Downcasting Example

• Upcasting does not risk the loss of precision nor require you

es
to specify the new data type in parentheses.

ss
la
C
ct
ra
st
Ab

21
Abstrac Class in Java
Page 22

Upcasting Example

• Even though CreditAccount is an Account, it was upcast to

es
Account so it lost access to its Credit Account specific

ss
methods and fields.

la
• Attempts to access subclass methods fail at compile time.

C
CreditAccount is a subclass of Account.

ct
Account is a superclass.
...
ra
Account account =
st
(Account) new CreditAccount("Sally Walls",66778,1000,500);
Ab

...
account.getcreditlimit();
...
Fails because the method belongs to the
CreditAccount subclass and access to it is lost
when upward casting.

22
Abstrac Class in Java
Page 23

Upcasting Example Explained

• The loss of precision in object assignments differs from

es
primitive data types.

ss
• Upcasting from a specialized subclass to a generalized

la
superclass loses access to the specialized variables and

C
methods. CreditAccount is a subclass of Account.

ct
Account is a superclass.
ra
...
Account account =
st
(Account) new CreditAccount("Sally Walls",66778,1000,500);
Ab

...
account.getcreditlimit();
...
Fails because the method belongs to the
CreditAccount subclass and access to it is lost
when upward casting.

23
Abstrac Class in Java
Page 24

Downcasting Example

• Downcasting the superclass works here because the runtime

es
object is actually a CreditAccount instance.

ss
• The Account instance is first cast to a subclass of itself before

la
running the CreditAccount instance method.

C
CreditAccount is a subclass of Account.

ct
Account is a superclass.
...
ra
Account account =
st
(Account) new CreditAccount("Sally Walls",66778,1000,500);
Ab

...
((CreditAccount)account).getcreditlimit();
...
Succeeds because the method belongs to the
CreditAccount subclass.

24
Abstrac Class in Java
Page 25

Downcasting Example Explained

• Downcasting from a generalized to specialized subclass

es
returns access to the specialized variables and methods if

ss
they were there from a previous upcast.

la
C
CreditAccount is a subclass of Account.

ct
Account is a superclass.
...
ra
Account account =
st
(Account) new CreditAccount("Sally Walls",66778,1000,500);
Ab

...
((CreditAccount)account).getcreditlimit();
...
Succeeds because the method belongs to the
CreditAccount subclass.

25
Abstrac Class in Java
Page 26

Terminology

Key terms used in this lesson included:

es
• Abstract class

ss
• instanceof

la
C
• Casting
• Downward cast
ct
ra
• Interface
st
Ab

• Upward cast
• Virtual method invocation

26
Abstrac Class in Java
Page 27

Summary

In this lesson, you should have learned how to:

es
• Model business problems using Java classes

ss
• Use Abstract Classes

la
C
• Use the instanceof operator to compare object types

ct
• Use virtual method invocation
ra
• Use upward and downward casts
st
Ab

27

You might also like