Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without...

29
Abstract Classes and Interfaces Mar 27, 2022

Transcript of Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without...

Abstract Classes and Interfaces

Apr 18, 2023

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

2

Abstract classes I

• 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

3

Abstract classes II• 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

4

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

5

An example abstract class

• public abstract class Animal { abstract int eat(); abstract void breathe();}

• This class cannot be instantiated• Any non-abstract subclass of Animal must

provide the eat() and breathe() methods

6

Why have abstract methods?

• Suppose there is a class Animal and there are few other classes like Cat, Dog and Horse. These classes extends Animal class so basically they are having few common habits(methods in technically) which they are inheriting from Animal class.

• Now, if you have understood the above example then you would have been able to figure out that creating object of Animal class has no significance as you can’t judge that the new object of Animal class will represent which animal.

• Hence for such kind of scenarios we generally creates an abstract class and later concrete classes extends these classes and overrides their methods accordingly and can have their own methods as well.

7

A problem• class Shape { ... }• class Star extends Shape {

void draw() { ... } ...}

• class Crescent extends Shape { void draw() { ... } ...}

• Shape someShape = new Star();– This is legal, because a Star is a Shape

• someShape.draw();– This is a syntax error, because some Shape might not have a draw()

method– Remember: A class knows its superclass, but not its subclasses

8

A solution• abstract class Shape {

abstract void draw();}

• class Star extends Shape { void draw() { ... } ...}

• class Crescent extends Shape { void draw() { ... } ...}

• Shape someShape = new Star();– This is legal, because a Star is a Shape– However, Shape someShape = new Shape(); is no longer legal

• someShape.draw();– This is legal, because every actual instance must have a draw() method

9

Points to remember about abstract class

• An abstract class has no use until unless it is extended by some other class.

• If you declare an abstract method in a class then you must declare the class abstract as well. you can’t have abstract method in a non-abstract class. It’s vice versa is not always true: If a class is not having any abstract method then also it can be marked as abstract.

• Abstract class can have non-abstract method (concrete) as well.

• Note: The class which is extending abstract class must override (or implement) all the abstract methods or should be made abstract too

10

Points to remember about abstract method

•1) Abstract method has no body.2) Always end the declaration with a semicolon(;).3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.4) Abstract method must be in a abstract class.

• syntax:– public abstract void display();

11

• Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You can say that it provides partial abstraction. Interfaces are used for 100% abstraction (full abstraction)

12

Interfaces• An interface declares (describes) methods but does not supply

bodies for them interface KeyListener {

public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e);}

• All the methods are implicitly public and abstract• You cannot instantiate an interface

– An interface is like a very abstract class—none of its methods are defined

• An interface may also contain constants (final variables)

13

Designing interfaces• Most of the time, you will use Sun-supplied Java interfaces• Sometimes you will want to design your own• You would write an interface if you want classes of various

types to all have a certain set of capabilities• For example, if you want to be able to create animated

displays of objects in a class, you might define an interface as:– public interface Animatable {

install(Panel p); display();}

• Now you can write code that will display any Animatable class in a Panel of your choice, simply by calling these methods

14

Implementing an interface I

• You extend a class, but you implement an interface

• A class can only extend (subclass) one other class, but it can implement as many interfaces as you like

• Example: class MyListener

implements KeyListener, ActionListener { … }

15

Implementing an interface II• When you say a class implements an

interface, you are promising to define all the methods that were declared in the interface

• Example: class MyKeyListener implements KeyListener {

public void keyPressed(KeyEvent e) {...}; public void keyReleased(KeyEvent e) {...}; public void keyTyped(KeyEvent e) {...};}

– The “...” indicates actual code that you must supply

• Now you can create a new MyKeyListener

16

Partially implementing an Interface

• It is possible to define some but not all of the methods defined in an interface:

abstract class MyKeyListener implements KeyListener { public void keyTyped(KeyEvent e) {...};}

• Since this class does not supply all the methods it has promised, it is an abstract class

• You must label it as such with the keyword abstract• You can even extend an interface (to add methods):– interface FunkyKeyListener extends KeyListener

{ ... }

17

What are interfaces for?• Reason 1: A class can only extend one other

class, but it can implement multiple interfaces– This lets the class fill multiple “roles”– In writing Applets, it is common to have one class

implement several different listeners– Example:

class MyApplet extends Applet implements ActionListener, KeyListener { ... }

• Reason 2: You can write methods that work for more than one kind of class

18

Interface and Inheritance

• public interface Inf1 {

public void method1(); } public interface Inf2 extends Inf1 {

public void method2(); } public class Demo implements Inf2{ public void method1() { //Implementation of method1 } public void method2() { //Implementation of method2 } }

19

key points to remember about interfaces:• 1) We can’t instantiate an interface in java.• 2) Interface provides complete abstraction as none of its methods

can have body. On the other hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.

• 3) implements keyword is used by classes to implement an interface.

• 4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.

• 5) Class implementing any interface must implement all the methods, otherwise the class should be declared as “abstract”.

• 6) Interface cannot be declared as private, protected or transient.• 7) All the interface methods are by default abstract and public• 8) Variables declared in interface are public, static and final by

default.• 9) Interface variables must be initialized at the time of declaration

otherwise compiler will through an error.

20

• 10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final.

• 11) Any interface can extend any other interface but cannot implement it. Class implements interface and interface extends interface.

• 12) A class can implements any number of interfaces.• 13) If there are having two or more same methods in two

interfaces and a class implements both interfaces, implementation of one method is enough.

• 14) Methods with same signature but different return type can’t be implemented at a time for two or more interfaces.

• 15) Variable names conflicts can be resolved by interface name

21

Benefits of having interfaces:

• Without bothering about the implementation part, we can achieve the security of implementation

• In java, multiple inheritance is not allowed, However by using interfaces you can achieve the same . A class can extend only one class but can implement any number of interfaces. It saves you from Deadly Diamond of death(DDD) problem.

22

instanceof• instanceof is a keyword that tells you whether a variable

“is a” member of a class or interface• For example, if

class Dog extends Animal implements Pet {...}Animal fido = new Dog();

then the following are all true: fido instanceof Dog fido instanceof Animal fido instanceof Pet

• instanceof is seldom usedclass Simple1{ public static void main(String args[]){ Simple1 s=new Simple1(); System.out.println(s instanceof Simple);//true } } 23

Interfaces, again

• When you implement an interface, you promise to define all the functions it declares

• There can be a lot of methods interface KeyListener {

public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e);}

• What if you only care about a couple of these methods?

24

Adapter classes• Solution: use an adapter class• An adapter class implements an interface and provides

empty method bodies class KeyAdapter implements KeyListener {

public void keyPressed(KeyEvent e) { }; public void keyReleased(KeyEvent e) { }; public void keyTyped(KeyEvent e) { };}

• You can override only the methods you care about

• Java provides a number of adapter classes

25

Vocabulary• abstract method—a method which is declared

but not defined (it has no method body)• abstract class—a class which either (1) contains

abstract methods, or (2) has been declared abstract

• instantiate—to create an instance (object) of a class

• interface—similar to a class, but contains only abstract methods (and possibly constants)

• adapter class—a class that implements an interface but has only empty method bodies

26

• Remember two rules:1) If the class is having few abstract methods and few concrete methods: declare it as abstract class.2) If the class is having only abstract methods: declare it as interface.

27

The End

Complexity has nothing to do with intelligence, simplicity does.        — Larry Bossidy

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

 — Antoine de Saint Exupery