8- Abstract & Interfaces

31
Abstract Classes •A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods then the class itself must be qualified as an abstract class. Definitio ns • Not able to implement some of the methods i.e. No content inside method, then declare it as abstract. (Its because the implementation is unclear).

description

easy

Transcript of 8- Abstract & Interfaces

Page 1: 8- Abstract & Interfaces

Abstract Classes

•A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods then the class itself must be qualified as an abstract class.

Definitions

• Not able to implement some of the methods i.e. No content inside method, then declare it as abstract. (Its because the implementation is unclear).

Page 2: 8- Abstract & Interfaces

• public interface Car {• int i=2;• void engine();• void body(); }

• public class Ford implements Car {• public void body() {System.out.println("Ford Body"); }• public void engine() { System.out.println("Ford Engine");}}

• public abstract class Maruthi implements Car {• public void body() {• System.out.println("Maruthi Body"); }• public void engine() { System.out.println("Maruthi engine");}• abstract void maruthiSpecificMethod();}

• public class Maruthi800 extends Maruthi {• void maruthiSpecificMethod() • {System.out.println("Maruthi Specific method"); }}

Page 3: 8- Abstract & Interfaces

• public class CarFactory {• public static void main(String[] args) {• //Maruthi m = new Maruthi();• //m.body();• //m.engine();• //Car c = new Maruthi();• Car c = getCar();• c.body();• c.engine();

– // c.i = 12;• //c.maruthiSpecificMethod();• //m.maruthiSpecificMethod();• }• static Car getCar(){• //Car c = new Ford();• Car c = new Maruthi800();• return c;}}

Page 4: 8- Abstract & Interfaces

• More about abstract• Interfaces and abstract classes provide a more structured way to separate interface

from implementation.

• Abstract class is a midway step between an interface and an ordinary class

• Since an abstract class is incomplete the compiler wont allow you to create an object of abstract class. If you inherit from an abstract class and want to create objects of the new type, you must provide method definitions for all the abstract methods in the base class. If you don’t then the derived class is also abstract and the compiler will force you to qualify that class with the abstract keyword.

BankAccount anaccount; //

anaccount = new BankAccount();// Error – Bank Account is abstract

anaccount = new SavingsAccount();//

anaccount = null;

• Its possible to make a class abstract without including any abstract methods. Its useful when you’ve got a class in which it doesn’t make any sense to have abstract methods, and you want to prevent any instances of that class.

Facts

Page 5: 8- Abstract & Interfaces

The reason for using abstract classes • The primary purpose of an abstract class is to provide a set of one or more public interface

methods whose implementations are expected to be found in some derived class further down the inheritance hierarchy. The key phrase is “expected to be found in some derived class further down the inheritance hierarchy". This means as a designer you would employ an abstract class in your application architecture when you want a base class to specify rather than implement behavior and you expect derived classes to actually implement the behavior specified by the base class

• Why create a class that does nothing but only specify set of interface metods?

Abstract class will comprise the upper tiers of your inheritance hierarchy.

The upper tiers of an inheritance hierarchy is where you expect to find specification for general behavior found in derived classes which comprise the lower tiers of an inheritance hierarchy.

Designing application architecture in this fashion .,ie abstraction at the top and concrete implementation at the bottom enables the architecture to accommodate new functionality rather than modified.

OO Design

Page 6: 8- Abstract & Interfaces

Abstract Classes

Driveabstract void read();abstract void write();

FloppyDrivevoid read() { System.out.println( “Magnetic disk read” );}void write() { System.out.println( “Magnetic disk write” );}

PenDrivevoid read() { System.out.println( “Flash memory read” );}void write() { System.out.println( “Flash memory write” );}

CDROMDrivevoid read() { System.out.println( “Optical disk read” );}void write() { System.out.println( “No write possible” );}

Abstract Classes are incomplete classes. The abstract methods has to be implemented by extending class

Abstract Classes cannot be instantiated, but an abstract class type object can hold its sub class type reference

Page 7: 8- Abstract & Interfaces

Using instanceof

class UsingInstanceOf {

public static void main(String[] args) {

Drive a = new PenDrive();

System.out.println(a instanceof PenDrive); // true

System.out.println(a instanceof Drive); // true

System.out.println(a instanceof Object); // true

System.out.println(a instanceof FloppyDrive); // false

}

}

Page 8: 8- Abstract & Interfaces

• General form to declare an abstract method:abstract type name (parameter-list);

• Ex: abstract void f();• No method body is present. Use abstract keyword

in front of class.• Abstract class cannot be directly instantiated with

the new operator. It can only be used as a super class for other classes that extend the abstract class.

• Any subclass of an abstract class must implement all of the abstract methods in the super class

• Purpose is to be extended (sub classed).

Page 9: 8- Abstract & Interfaces

• Must be sub classed and actual implementations must be provided for the abstract methods.

• Any implementation specified can be overridden by additional subclasses.

• An object must have an implementation for all of its methods.

• We have to create a subclass that provides an implementation for the abstract method.

• Examples (Programs)

Page 10: 8- Abstract & Interfaces

• You can't mark a class as both abstract and final. An abstract class must be sub classed, whereas a final class must not be sub classed.

• public abstract final class Maruthi implements Car // Not Possible

Page 11: 8- Abstract & Interfaces

• // A Simple demonstration of abstract.• abstract class A {• abstract void callme();• // concrete methods are still allowed in abstract classes• void callmetoo() {• System.out.println("This is a concrete method.");• }• }• class B extends A {• void callme() {• System.out.println("B's implementation of callme.");• }• }• class AbstractDemo {• public static void main(String args[]) {• B b = new B();• b.callme();• b.callmetoo();• }• }

Page 12: 8- Abstract & Interfaces

• // Using abstract methods and classes.• abstract class Figure {• double dim1;double dim2;• Figure(double a, double b) {dim1 = a;• dim2 = b;• }// area is now an abstract method• abstract double area();}class Rectangle extends Figure {Rectangle(double a, double b)

{super(a, b);}• // override area for rectangle• double area() {System.out.println("Inside Area for Rectangle.");return dim1 * dim2;}}• class Triangle extends Figure {Triangle(double a, double b) {super(a, b);}• // override area for right triangle• double area() {System.out.println("Inside Area for Triangle.");return dim1 * dim2 / 2;• }• } class AbstractAreas {public static void main(String args[]) {• // Figure f = new Figure(10, 10); // illegal now• Rectangle r = new Rectangle(9, 5); • Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created• figref = r; System.out.println("Area is " + figref.area());• figref = t;System.out.println("Area is " + figref.area());• }• }

Page 13: 8- Abstract & Interfaces

• interface is nothing but the collection of methods with empty implementations and constants variables ( variables with static and final declarations ).

• can specify what a class must do, but not how it does it.• concrete - abstract - interfaceInterface Definition• visibility mode interface interfaceName{

        constant variable declarations        abstract method declarations} e.g. public interface RacingCar{  public void startcar (int Obj);   public void changegear (int Obj);   public void incrrace (int Obj);  public void stopcar (int Obj);}

Interface

Page 14: 8- Abstract & Interfaces

No Multiple Inheritance Support

Employee

Associate Trainer ProjectManager

SportsPerson

• Java doesn’t support Multiple Inheritance

• Instead it uses interfaces to implement multiple behaviours to a class

• A class in Java cannot have more than one super class

Page 15: 8- Abstract & Interfaces

Employee

Associate Trainer ProjectManager

SportsPerson

Need of Interface

This should be aninterface

Page 16: 8- Abstract & Interfaces

Interfaces

• Interfaces are complete abstract classes and contains only method declarations and constant declarations– All method declarations are implicitly public

and abstract– All constant declarations are implicitly public

and final

• A class that implements an interface should give implementation (concrete methods) for all the methods in that interface

Page 17: 8- Abstract & Interfaces

Creating Interfaces

• interface keyword is used

Syntax:

[public] interface InterfaceName {

data-type variable = value;

return-type method1(arguments);

return-type method2(arguments); // so on…

}

Page 18: 8- Abstract & Interfaces

Implementing an Interface to a Class

• implements keyword is used to implement an interface to a class

[public] class ClassName implements InterfaceName {

// Concrete implementations of methods

// declared in the interface

}

Page 19: 8- Abstract & Interfaces

• /*• Java Interface example.• This Java Interface example describes how interface is defined and • being used in Java language.•  Syntax of defining java interface is,• <modifier> interface <interface-name>{•   //members and methods()• }• */•  • //declare an interface• interface IntExample{•  • /*•   Syntax to declare method in java interface is,•   <modifier> <return-type> methodName(<optional-parameters>);•   IMPORTANT : Methods declared in the interface are implicitly public and abstract.•   */•  • public void sayHello();• }• }

Page 20: 8- Abstract & Interfaces

• /*• Classes are extended while interfaces are implemented. • To implement an interface use implements keyword.• IMPORTANT : A class can extend only one other class, while it • can implement n number of interfaces.• */•  • public class JavaInterfaceExample implements IntExample{• /*•   We have to define the method declared in implemented interface,•   or else we have to declare the implementing class as abstract class.•   */•  • public void sayHello(){• System.out.println("Hello Visitor !");• }•  • public static void main(String args[]){• //create object of the class• JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();• //invoke sayHello(), declared in IntExample interface.• javaInterfaceExample.sayHello();• }• }•  • /*• OUTPUT of the above given Java Interface example would be :• Hello Visitor !• */

Page 21: 8- Abstract & Interfaces

• An interface forms a set of rules that a class should follow (implement), to get classified under that interface

• Using interfaces, the classes that falls under different Inheritance Hierarchy, can share common behaviours with their own implementation (or) Logically groups the classes on their behaviours. Thus simulates multiple inheritance

• Generally behaviours of classes are abstracted as interfaces

Page 22: 8- Abstract & Interfaces

Thing

Vehicle Building

LivingThing NonLivingThing

Animal Bird

CarAirplane BusBoth can flyBut in

different waysCan be classified under

an interface Flyable

Page 23: 8- Abstract & Interfaces

Example

interface Flyable {

void fly();

}

Page 24: 8- Abstract & Interfaces

Example

class Bird extends LivingThing implements Flyable {

public void fly() {

System.out.println(“Birds fly naturally”);

}

}

Page 25: 8- Abstract & Interfaces

Example

class Airplane extends Vehicle implements Flyable {

public void fly() { System.out.println( “Airplanes fly artificially” ); }}

Page 26: 8- Abstract & Interfaces

Example

class UsingFlyables { public static void main(String args[]) { Airplane a = new Airplane(); //NonLivingThing Bird b = new Bird(); //LivingThing Flyable f = a; //Classified under Flyable f.fly(); // Calls Airplane’s version of fly() f = b; f.fly(); // Calls Bird’s version of fly() }}

Page 27: 8- Abstract & Interfaces

• interface i1 {• int a =99;• static final int b = 88;• void m1();• void m2();• }• class B implements i1 {• public void m1()• {• System.out.println(a);• System.out.println("m1");• }• public void m2() {• System.out.println(b);• System.out.println("m2");• }• }• class test • {• public static void main (String args[]) • {• i1 obj = null;• System.out.println(obj.a);• System.out.println();• System.out.println(obj.b);• System.out.println();• System.out.println(i1.a);• System.out.println();• System.out.println(i1.b);• obj = new B();• obj.m1();• System.out.println();• obj.m2();• }• }

Page 28: 8- Abstract & Interfaces

• interface i1 • {int a = 99;int c = 111;void m1();void m3();• }• interface i2 {int b = 88;int c = 222;void m2();void m4();}

• class Hello implements i1,i2 {• public void m1() {• System.out.println(a +" " + b+ " m1"); System.out.println(i1.c); System.out.println(i2.c);• // System.out.println(c);}

• public void m2() { System.out.println(a +" " + b+ " m2"); System.out.println(i1.c + " " +i2.c); }

• public void m3() { System.out.println("m3"); }

• public void m4() { System.out.println("m4"); } }

• class itest {• public static void main (String args[]) {• i1 obj = new Hello();• obj.m1();• obj.m3();• i2 obj1 = new Hello();• obj1.m2();• obj1.m4();• }• }

Page 29: 8- Abstract & Interfaces

• //One interface can extend another.

• interface A {

• void meth1();

• void meth2();

• } // B now includes meth1() and meth2() -- it adds meth3().

• interface AA {

• void meth1();

• void meth2();

• }

• interface B1 extends A, AA {

• void meth3();

• } // This class must implement all of A and B

• class MyClass implements B1 {

• public void meth1() { System.out.println("Implement meth1()."); }

• public void meth2() { System.out.println("Implement meth2()."); }

• public void meth3() { System.out.println("Implement meth3()."); }

• }class IFExtend {

• public static void main(String arg[]) {

• MyClass ob = new MyClass();

• ob.meth1();

• ob.meth2();

• ob.meth3();

• }

• }

Page 30: 8- Abstract & Interfaces

Marker Interfaces

• An interface that doesn’t contain any declaration

• Empty interfaces

• Used to mark the classes to group under another name

Page 31: 8- Abstract & Interfaces

Abstract class Interface

Have executable methods and abstract methods.

Have no implementation code. All methods are abstract.

Can only subclass one abstract class. (Can extend only one class)

A class can implement any number of interfaces.

Can have instance variables, Cannot have instance variables,

constructors and any visibility: public, private, protected, none (aka package).

can have only public and none (aka package) visibility.