0% found this document useful (0 votes)
12 views

Unit 5 Interface2

Ldco

Uploaded by

lesterxd60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit 5 Interface2

Ldco

Uploaded by

lesterxd60
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Unit 4

Abstract class & Interface

Ms. Kashmira Jayakar


Ways to achieve Abstraction

There are two ways to achieve abstraction in


java
• Abstract class (0 to 100%)
• Interface (100%)
Abstraction
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
• Another way, it shows only essential things to
the user and hides the internal details, for
example, sending SMS where you type the
text and send the message. You don't know
the internal processing about the message
delivery.
Abstraction
• The interface in Java is a mechanism to
achieve abstraction. There can be only
abstract methods in the Java interface, not
method body. It is used to achieve abstraction
and multiple inheritance in Java.
• In other words, you can say that interfaces can
have abstract methods and variables. It
cannot have a method body.
Abstract class
• A class which is declared as abstract is known
as an abstract class. It can have abstract and
non-abstract methods. It needs to be
extended and its method implemented. It
cannot be instantiated.
Abstract class
• An abstract class must be declared with an
abstract keyword.
• It can have abstract and non-abstract
methods.
• It cannot be instantiated.
• It can have constructors and static methods
also.
• It can have final methods which will force the
subclass not to change the body of the
method.
Abstract class
• Abstract Method in Java
• A method which is declared as abstract and
does not have implementation is known as an
abstract method.

Eg.abstract void printStatus();//no method body


and abstract
abstract class Bank{ System.out.println("Rate of Interest is:
abstract int getRateOfInterest(); "+b.getRateOfInterest()+" %");
} }}
class SBI extends Bank{
int getRateOfInterest(){return 7;} Output:-
} Rate of Interest is: 7 %
class PNB extends Bank{ Rate of Interest is: 8 %
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is:
"+b.getRateOfInterest()+" %");
b=new PNB();
Abstract class having constructor,
data member and methods
• An abstract class can have a data member,
abstract method, method body (non-abstract
method), constructor, and even main()
method.
• If there is an abstract method in a class, that
class must be abstract.
• If you are extending an abstract class that has
an abstract method, you must either provide
the implementation of the method or make
this class abstract.
//Example of an abstract class that has class TestAbstraction2{
abstract and non- public static void main(String args[]){
abstract methods Bike obj = new Honda();
abstract class Bike{ obj.run();
Bike(){System.out.println("bike is cre obj.changeGear();
ated");}
}
abstract void run();
}
void changeGear(){System.out.printl
n("gear changed");} Output:-
}
//Creating a Child class which inherits bike is created
Abstract class running safely..
class Honda extends Bike{ gear changed
void run(){System.out.println("runnin
g safely..");}
}
//Creating a Test class which calls abstr
act and non-abstract methods
• Java Interface also represents the IS-A
relationship.
Why use Java interface?

• It is used to achieve abstraction.


• By interface, we can support the functionality
of multiple inheritance.
• It can be used to achieve loose coupling.
• An interface is declared by using the interface
keyword. It provides total abstraction; means
all the methods in an interface are declared
with the empty body, and all the fields are
public, static and final by default. A class that
implements an interface must implement all
the methods declared in the interface.
syntax
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
• The Java compiler adds public and abstract
keywords before the interface method.
Moreover, it adds public, static and final
keywords before data members.
• In other words, Interface fields are public,
static and final by default, and the methods
are public and abstract.
The relationship between classes and
interfaces
Interface
interface printable{
void print();
}

class A6 implements printable{


public void print(){System.out.println("Hello world");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Outout:--
Hello world
Multiple inheritance in Java by
interface
interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
• Output:Hello Welcome
Interface inheritance
interface Printable{ obj.print();
void print(); obj.show();
} }
interface Showable extends Printable{ }
void show(); Output:-
} Hello
class TestInterface4 implements Showa Welcome
ble{
public void print(){System.out.println("
Hello");}
public void show(){System.out.println("
Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterf
ace4();
Abstract class Interface

1) Abstract class can have abstract Interface can have only


and non-abstract methods. abstract methods. Since Java 8, it
can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple
multiple inheritance. inheritance.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
6) An abstract class can extend An interface can extend another Java
another Java class and implement interface only.
multiple Java interfaces.
Abstract class Interface

7) An abstract class can be extended An interface can be implemented


using keyword "extends". using keyword "implements".

) A Java abstract class can have Members of a Java interface are public
class members like private, protected, by default.
etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Polymorphism
• Polymorphism means perform single action in
different ways.
• The word "poly" means many and "morphs"
means forms.

• Types of Java polymorphism


1. Compile-time Polymorphism-(Method
overloading)
2. Runtime Polymorphism-(Method overriding)
Compile-time polymorphism
• Compile-time polymorphism is also known as
static polymorphism or early binding.
• Compile-time polymorphism is a
polymorphism that is resolved during the
compilation process.
• Compile-time polymorphism is achieved
by method overloading in java
Method overloading by changing the number
of parameters
// Java program to demonstrate the working function**\nnumber 1 : " + num1
of method
// overloading by changing the number of + " \nnumber 2 : " + num2);
parameters }

public class MethodOverloading { public static void main(String[] args)


{
// 1 parameter MethodOverloading obj = new
void show(int num1) MethodOverloading();
{
System.out.println("number 1 : " + // 1st show function
num1); obj.show(3);
}
// 2nd show function
// 2 parameter obj.show(4, 5);
void show(int num1, int num2) }
{ }
System.out.println("\n **In Second
Compile time polymorphism
Method overloading by changing
Datatype of parameter
public class MethodOverloading12 { public static void main(String[] args)
{
// arguments of this function are of integer type // 1st show function
static void show(int a, int b) show(1, 2);
{
System.out.println("This is integer function "); // 2nd show function
int c=a+b; show(1.2, 2.4);
System.out.println("interger addiction is " +c); }
}
}

// argument of this function are of float type


static void show(double a, double b)
{
System.out.println("This is double function ");
double c=a+b;
System.out.println("float addiction is " +c);
}
Compile time polymorphism
Advantages of Compile-time
Polymorphism:
1. It improves code clarity and allows for the
use of a single name for similar procedures.
2. It has a faster execution time since it is
discovered early in the compilation process.
3. Code Reusability
4. Flexibility and Convenience
• The only disadvantage of compile-time
polymorphism is that it doesn’t include
inheritance.
Run-time polymorphism
• Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime
rather than compile-time.
• In this process, an overridden method is called
through the reference variable of a superclass.
The determination of the method to be called
is based on the object being referred to by
the reference variable.
Run-time polymorphism
• Upcasting
• If the reference variable of Parent class refers
to the object of Child class, it is known as
upcasting
• class A{}
• class B extends A{}
• A a=new B();//upcasting
Runtime Polymorphism

class Shape{ class TestPolymorphism2{


void public static void main(String args[]){
draw(){System.out.println("drawing...") Shape s;
;} s=new Rectangle();
} s.draw();
class Rectangle extends Shape{ s=new Circle();
void draw(){System.out.println("drawing s.draw();
rectangle...");}
} s=new Triangle();
class Circle extends Shape{ s.draw();
void draw(){System.out.println("drawing }
circle...");} }
}
class Triangle extends Shape{
void draw(){System.out.println("drawing
triangle...");}
}
Runtime Polymorphism
Runtime Polymorphism with
Multilevel Inheritance
class Animal {
{ void eat()
void eat() {
{ System.out.println("drinking milk");
System.out.println("eating"); }
}
} public static void main(String
args[])
class Dog extends Animal {
{ Animal a1,a2,a3;
void eat() a1=new Animal();
{ a2=new Dog();
System.out.println("eating fruits"); a3=new BabyDog();
} a1.eat();
} a2.eat();
a3.eat();
class BabyDog extends Dog }
}
Runtime Polymorphism with
Multilevel Inheritance
Difference Compile time & runtime
Polymorphism
Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, the call is resolved by the In Run time Polymorphism, the call is not resolved by the
compiler. compiler.

It is also known as Static binding, Early binding and It is also known as Dynamic binding, Late binding and
overloading as well. overriding as well.

Method overloading is the compile-time polymorphism Method overriding is the runtime polymorphism having the
where more than one methods share the same name with same method with same parameters or signature but
different parameters or signature and different return type. associated withcompared, different classes.

It is achieved by function overloading and operator


It is achieved by virtual functions and pointers.
overloading.

It provides slow execution as compare to early binding


It provides fast execution because the method that needs to
because the method that needs to be executed is known at
be executed is known early at the compile time.
the runtime.

Compile time polymorphism is less flexible as all things Run time polymorphism is more flexible as all things execute
execute at compile time. at run time.

Inheritance is not involved. Inheritance is involved.

You might also like