Chapter6 OOP Part4 Interfaces

You might also like

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

Abstract Classes

and Interfaces

1
Abstract classes

2
Abstract methods
You can declare an object without defining it:
Person p;
Similarly, you can declare a method without
defining it:
public abstract void draw(int size);
◦ Notice that the body of the method is missing
A method that has been declared but not defined is
an abstract method

3
Abstract classes
Any class containing an abstract method is an
abstract class
You must declare the class with the keyword
abstract:
◦ abstract class MyClass {...}
An abstract class is incomplete
◦ It has “missing” method bodies
You cannot instantiate (create a new instance of)
an abstract class

4
Abstract classes
You can extend (subclass) an abstract class
◦ If the subclass defines all the inherited abstract
methods, it is “complete” and can be instantiated
◦ If the subclass does not define all the inherited
abstract methods, it too must be abstract
You can declare a class to be abstract even if
it does not contain any abstract methods
◦ This prevents the class from being instantiated

5
Why have abstract classes?
Suppose you wanted to create a class Shape, with
subclasses Oval, Rectangle, Triangle, Hexagon, etc.
You don’t want to allow creation of a “Shape”
◦ Only particular shapes make sense, not generic ones
◦ If Shape is abstract, you can’t create a new Shape
◦ You can create a new Oval, a new Rectangle, etc.

Abstract classes are good for defining a general category


containing specific, “concrete” classes

6
A problem
Suppose you have a class Shape, but it
isn’t abstract
◦ Shape should not have a draw() method
Shape someShape
◦ Each subclass of Shape should have a someShape.draw();
= new Star();
draw() method
• This is legal, • This is a
because a Star is a compilation error,
Shape because Shape
class Shape { ... } (Remember class doesn't not
class Star extends Shape { Polymorphism !) have a draw()
void draw() { ... } method
... • don’t forget that
} instantiation of
object happens at
class Crescent extends Shape { run-time.
void draw() { ... }
...
}

7
A solution
abstract class Shape {
abstract void draw();
}
Shape someShape
class Star extends Shape { someShape.draw();
= new Star();
void draw() { ... }
• This is legal, • This is legal,
... because a Star is a because every
} Shape actual instance
• However, Shape must have a
class Crescent extends Shape { someShape = new draw() method
void draw() { ... } Shape(); is no
longer legal
...
}

8
Interfaces

9
Interfaces
An interface declares (describes) All the methods are implicitly
methods but does not supply public and abstract
bodies for them ◦ You can add these qualifiers if you
like, but why bother?
interface KeyListener {
public void You cannot instantiate an interface
keyPressed(KeyEvent e); ◦ An interface is like a very abstract
public void class—none of its methods are
keyReleased(KeyEvent e); defined
public void keyTyped(KeyEvent
e); An interface may also contain
} constants (final variables)

10
Designing interfaces
Most of the time, you will Syntax:
use existing Java interfaces ◦ public interface Interface_name
{
Sometimes you will want to Method1(..);
design your own Method2(..);
}
Write an interface if you
want classes of various types
to all have a certain set of
capabilities

11
Designing interfaces
Variables declared in interface
are public, static and final by default.

Interface variables must be initialized


at the time of declaration otherwise
compiler will throw an error.

12
Designing interfaces

The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data
members.

13
Implementing an Interface
You extend a class, but you implement an interface

When you say a class implements an interface, you are


promising to define all the methods that were declared in
the interface

Example:
class MyListener
implements KeyListener, ActionListener { … }

14
Example
interface Drawable{
void draw();
}

class Rectangle implements Drawable{


public void draw(){System.out.println("drawing rectangle");}
}

class Circle implements Drawable{


public void draw(){System.out.println("drawing circle");}
}

//Using interface
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}
}

15
What are interfaces for?
we can achieve the security of implementation (you
can see it as a contract that all the classes should
respect)
In java, multiple inheritance is not allowed, however
you can use interface to make use of it as you can
implement more than one interface.
Java Interface also represents the IS-A relationship.

16
Why use Java interface?

17
Interface vs. abstract class
Interface Abstract class
Fields Only constants Constants and variable
data

Methods cannot contain Abstract or concrete


concrete(with
implementation)
methods

18
Interface vs. class
Interface class
An interface can extend multiple A subclass can inherit only ONE class
interfaces ! !
An interface Cannot extend a class A class Can implement numerous
interfaces
In an interface, you can't instantiate In class, you can instantiate variable
variable and create an object. and create an object.

only one access specifier is used- All access specifiers are allowed:
Public. private, protected and public.

19
Implementations as contracts
A class which realizes an interface A class can implement many
must provide an implementation interfaces.
of every method defined within
the interface
◦ A class may implement some An Interface can extend multiple
additional methods (but these Interfaces.
extra methods aren’t accessible
through this interface) ◦ Extension is the preferred way to
add new methods to an Interface.
◦ Beware: adding another method to
an existing Interface will “break”
every current implementation of
this Interface!

20
class implementing many
interfaces Example
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

21
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

22
Interfaces in Java 8
In any OO • cannot be instantiated, and
• defines a “contract” which any realization of
language, the interface must fulfil.
• In Java, a realization is denoted by the keyword
an interface implements.

In Java 8, an • default implementations of instance methods,


interface and
• implementations of static methods.
may contain

23
Default Methods
Problem
• Pre-Java 8 interfaces couldn’t have method bodies.
• The only way to add functionality to Interfaces
was to declare additional methods which would be
implemented in classes that implement the
interface
• It is impossible to add methods to an interface
without breaking the existing implementation

24
Default Methods
Solution
• Default Methods!
• Java 8 allows default methods to be added to
interfaces with their full implementation
• Classes which implement the interface don’t have
to have implementations of the default method
• Allows the addition of functionality to interfaces
while preserving backward compatibility

25
Default Methods
Example

public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
}
public class Clazz implements A {}
• Then in the main method:
Clazz clazz = new Clazz();
clazz.foo(); // Calling A.foo()

The implementation of the foo() method belongs to all the classes that implement
the interface A. You must create objects in order to call a default method

26
Static methods in an interface
Static methods
• don't belong to a particular object
• Not part of the API of the classes
implementing the interface
• must be called by using the interface
name preceding the method name.

27
Example for default and static
methods
interface MyInterface {

default void newMethod() {


System.out.println("Newly added default method");
}

static void anotherNewMethod() {


System.out.println("Newly added static method");
}

void exisitingMethod(String str);


}

28
Example for default and static
methods
public class Example implements MyInterface{

public void existingMethod(String str){


System.out.println(str);
}

public static void main(String[] args) {


Example obj = new Example();

Obj.newMethod();

MyInterface.anotherNewMethod();

obj.existingMethod("Java");
}
}

29
Comparable interface
Used to order the objects of the user-defined class.
You can sort the elements based on single data member only.
For example, it may be name, or age or anything else.
int compareTo (Object o)
◦ It is used to compare the current object with the specified object. It returns:
◦ positive integer, if the current object is greater than the specified object.
◦ negative integer, if the current object is less than the specified object.
◦ zero, if the current object is equal to the specified object.

30
Comparable interface Example
class Student implements Comparable<Student> { import java.util.*;
int rollno;
String name; public class TestSort1 {
int age;
public static void main(String args[]) {
Student(int rollno, String name, int age) {
this.rollno = rollno; Student al = new Student[3];
this.name = name;
a1[0] = new Student(101, "Med", 23);
this.age = age;
} a1[1] = new Student(106, "Ali", 27);

public int compareTo(Student st) { a1[2] = new Student(105, "Sonia", 21);


if (age == st.age)
return 0;
Arrays.sort(al);
else if (age > st.age)
return 1; for (Student st : al) {
else
return -1; System.out.println(st.rollno + " "
} + st.name + " " + st.age);
}
}

}
}

31

You might also like