[go: up one dir, main page]

0% found this document useful (0 votes)
12 views23 pages

CS102 Chapter5 ABSTRACT CLASSES AND INTERFACES

This document covers abstract classes and interfaces in Java, explaining their definitions, syntax, and usage. It provides examples of abstract classes, their inheritance, and the implementation of interfaces, highlighting the differences between them. Additionally, it discusses the final modifier and includes exercises for practical application of the concepts.

Uploaded by

lemoned
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)
12 views23 pages

CS102 Chapter5 ABSTRACT CLASSES AND INTERFACES

This document covers abstract classes and interfaces in Java, explaining their definitions, syntax, and usage. It provides examples of abstract classes, their inheritance, and the implementation of interfaces, highlighting the differences between them. Additionally, it discusses the final modifier and includes exercises for practical application of the concepts.

Uploaded by

lemoned
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/ 23

CS102 OBJECT ORIENTED PROGRAMMING

CHAPTER 5
ABSTRACT CLASSES AND INTERFACES

07/11/2021 1
07/11/2021 OBJECT ORIENTED PROGRAMMING 2
Abstract Classes
Any class which contains at least a single abstract method is an abstract class.

Declaring Abstract Classes in Java


Syntax of Java Abstract Class:
abstract class <class-name>
{
//class definition

Syntax of Java Abstract Method:


abstract <return-type><method-name>(<parameters>);

Example
abstract int calculate();

07/11/2021 OBJECT ORIENTED PROGRAMMING 3


Abstract Classes - Example

07/11/2021 OBJECT ORIENTED PROGRAMMING 4


Abstract Classes - Example public class Multiplication extends MyTest
public abstract class MyTest {
{ void calculate(int a, int b)
abstract void calculate(int a, int b); // No body. {
} int z = a * b;
public class Addition extends MyTest System.out.println(“Multiply: ” +z); }
{ }
void calculate(int a, int b) public class MyClass {
{ public static void main(String[] args)
int x = a + b; {
System.out.println(“Sum: ” +x); } // Creating objects of classes.
} Addition a = new Addition();
public class Subtraction extends MyTest Subtraction s = new Subtraction();
{ Multiplication m = new Multiplication();
void calculate(int a, int b)
{ // Calling methods by passing argument values.
int y = a - b; a.calculate(20, 30);
System.out.println(“Subtract: ” +y); } s.calculate(10, 5);
} m.calculate(10, 20);
}
}
07/11/2021 OBJECT ORIENTED PROGRAMMING 5
Abstract classes
In classical classes (normal), everything must be concrete
➢ All methods could be defined (signature and code)

➢ May have/include different visibility modifiers

An abstract class allows to create a halfway type


➢ It may contain abstract methods
➢ It is considered as partially implemented, and thus non-instantiable
➢ It may eventually have no abstract method
➢ The keyword abstract makes it non-instantiable
➢ We force the inheritence

07/11/2021 OBJECT ORIENTED PROGRAMMING 6


Abstract class :Example
public abstract class GeometricShape {
public double dim;
public GeometricShape (double x ) {
this.dim = x ; }
public void D i s p l a y( ) {
S y s t e m . o u t . p r i n t l n ( “ I ama geometric shape from unknown t y p e ” ) ; }
public abstract double S u r f a c e ( ) ; / / w i t h o u t implementation
}

public class C i r c l e extends GeometricShape {


public Circle(double x ) {
s u p e r ( x) ; }
public void D i s p l a y( ) {
S y s t e m . o u t . p r i n t l n ( “ I ama c i r c l e o f radius ” + super.dim); }
public double Surf ace() {
r e t u r n (super.dim * 3 . 1 4 ) ; }
}

public class Rectangle extends GeometricShape {


public double dim2;
public Rectangle(double x , double y ) {
s u p e r ( x) ;
th is. d im 2 = y ; }
public void Display ( ) {a
S y s t e m . o u t . p r i n t l n ( “ I ama rectangle o f dimensions ” + super.dim + “and” + dim2); }
public double Surf ace() {
r e t u r n (super.dim * dim2); } }

07/11/2021 OBJECT ORIENTED PROGRAMMING 7


Abstract class:Remarks
Generally:
➢ An abstract class may inherit from another abstract class;

➢ An abstract class may inherit from a concrete class;

➢ A concrete class inheriting from one or multiple abstract classes (indirectly), should implement all
the existing abstract methods

Using/defining an abstract class can be justified by:


➢ The current class will be inherited by many other classes;

➢ Abstract classes will be used throw commun methods having the same name.

For these two reasons, it is interesting tu define abstract classes.


07/11/2021 OBJECT ORIENTED PROGRAMMING 8
Final modifier
The keyword final may be applied to :

➢ Class variables

➢ Instance variables

➢ Local variables

➢ Methods

➢ Method’s parameters

➢ Classes

We are not allowed to modify final entites

07/11/2021 OBJECT ORIENTED PROGRAMMING 9


Final modifier

07/11/2021 OBJECT ORIENTED PROGRAMMING 10


Final variables
A final variable is a variable which cannot be modified once initialized.
Constants are qualified as final and static.

Example : public static final float pi = 3.14;

Example
class Test {
// Declaring and initializing static final variable
static final int CAPACITY = 4;

public static void main(String args[])


{
// Re-assigning final variable will throw compile-time error
CAPACITY = 5;
}
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 11


Final methods &classes

A final method cannot be redefined (overrided) in other sub-classes.

A final class
➢ Cannot be modified,

➢ Cannot be inherited (no sub-classes to be defined).

07/11/2021 OBJECT ORIENTED PROGRAMMING 12


Abstract class - Exercise

Based on inheritance and override method concept,


write a java program that represents the following
classes: Shape (abstract class), Rectangle and Triangle
(two concrete classes).

07/11/2021 OBJECT ORIENTED PROGRAMMING 13


Interfaces
• An interface is a completely "abstract class" that is used to group related methods with empty bodies
• Interfaces specify what a class must do and not how. It is the blueprint of the class.
Syntax
[public] interface myInterface {
//methods and/or static fields
}

Example
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 14


Interfaces
To access the interface methods, the interface must be "implemented" by another class with the
implements keyword (instead of extends).
The body of the interface method is provided by the "implement" class.
Example
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
class Pig implements Animal { public static void main(String[] args) {
public void animalSound() { Pig myPig = new Pig(); // Create a Pig object
System.out.println("The pig says: wee wee"); myPig.animalSound();
} myPig.sleep(); }
public void sleep() { }
System.out.println("Zzz"); }
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 15


Interfaces
✓ Like abstract classes, interfaces cannot be used to create dynamically objects
✓ Interface methods do not have a body - the body is provided by the "implement" clas
(except for final methods )
✓ On implementation of an interface, you must override all of its methods
✓ Interface methods are by default abstract and public
✓ Interface attributes are by default public, static and final
✓ An interface cannot contain a constructor (as it cannot be used to create objects)

07/11/2021 OBJECT ORIENTED PROGRAMMING 16


Interfaces
Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an object
(interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class can implement
multiple interfaces.

Note: To implement multiple interfaces, separate them with a comma.


class myClass [extends mySuperClass] [implements I n terface1, I n terface2, ...] {
…..
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 17


Interfaces
• An interface may inherit from one or multiple other interfaces. But it cannot inherit from a
class (concrete or abstract).
[public] interface myInterface [extends Interface1, Interface2 . . . ] {
/ / methods and/or s t a t i c f i e l d s
}
• A class cannot inherit from an interface, but it implements it. We use the keyword implements.

• A concrete class should provide an implementation for all the methods declared in the interfaces in
question as well as those declared in its super-classes (abstract).

Why interfaces instead of abstract classes?


Abstract classes may contain non-final variables, whereas variables in interface are final, public and static.

07/11/2021 OBJECT ORIENTED PROGRAMMING 18


Interfaces
Interfaces are declared using the keyword interface instead of class and are
integrated in other classes thanks to the keyword implements.
An interface is implicity declared as abstract ➔ the keyword abstract may be
omitted from the signatures of the methods.
All the interfaces’ methods to implement should be public.
In interfaces, a private method is useless as it cannot be implemented later in other
classes.

07/11/2021 OBJECT ORIENTED PROGRAMMING 19


Interfaces

07/11/2021 OBJECT ORIENTED PROGRAMMING 20


Example: Description and implementation of an interface
public i n t e r f a c e Screen {
public void d i s p l ay( S tri ng s ) ;
public void warning();
}
class Phone implements Screen {
public void d i s p l ay( S tr ing s ) {
System.out.println(s) ; }
public void warning() {
display(”phone Warning ! ! ” ) ; }
void r i n g ( ) {
System.out.println(”bip c a l l ! ! ” ) ; }
}

class Computer implements Screen {


String Name;
public Computer(String n) {
this.name = n ; }
public void d i s p l ay( S tri ng s ) {
System.out.p r i n t ln (“comput e r name : “+ s ) ; }
void warning ( ) {
System.out.println(”Warning from computer : ” + name);
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 21


/* Declaring a reference of the Screen interface */
class Main {
public static void main (String [] args) {
Screen sc ; //possible
Screen sc = new Screen (); //Error
sc.display(”my screen”); // not possible
// Instantiate a class implementing an interface Output:
Phone t = new Phone (); //OK bip call !!
t.ring(); phone Warning !!
Screen sc1 = t; // OK bip call !!
sc1.warning(); computer name : hp

if (sc1 instanceof Phone) {


Phone ph1=(Phone)sc1;
ph1.ring(); }

Screen sc2 = new Computer("My computer"); // OK


sc2.display("hp"); }
}

07/11/2021 OBJECT ORIENTED PROGRAMMING 22


Interfaces- Exercise
Write a Java program to create a banking system with three classes - Bank, SavingsAccount, and CurrentAccount.
Account should be an interface with methods to deposit, withdraw.
The bank should have a private double balance variable, a getBalance, setBalance methods and a
printAccountBalance method (void).
SavingsAccount and CurrentAccount should inherit the Bank class and implement the Account interface and have
their own private double variables interestRate and overdraftLimit respectively, and methods like applyInterest and
setOverdraftLimit respectively.
Create a Main class including the main program in which we will create an array of two Banking accounts: savings
and Current accounts.
For the savings account, we will call the method deposit with an amount of 1500.0, and for the Current account we
will call the method withdraw with an amount of 500.0.
Finally, we will print the new balance amount for both accounts.

07/11/2021 OBJECT ORIENTED PROGRAMMING 23

You might also like