Lecture 10
Lecture 10
Unit 1
Lecture 10
Lecture 10
• Abstraction
• Interfaces
• Abstract Class
Abstraction in Java
class TestBank{
public static void main(String args[]){
SBI b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println("Rate of Interest is: "+interest+" %");
}}
An abstract class can have data member, abstract method, method
body, constructor and even main() method.
File: TestAbstraction2.java
//example of abstract class that have method body
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
• Rule: If you are extending any abstract class
that have abstract method, you must either
provide the implementation of the method
or make this class abstract.
• Rule: If there is any abstract method in a
class, that class must be abstract.
The abstract class can also be used to provide some
implementation of the interface. In such case, the end
user may not be forced to override all the methods of
the interface.
interface A{
void a();
void b();
void c();
void d();
}
class Test5{
public static void main(String args[]){
M a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Interface in Java
• An interface in java is a blueprint of a class. It has
static constants and abstract methods only.
• The interface in java is a mechanism to achieve
fully abstraction. There can be only abstract
methods in the java interface not method body. It
is used to achieve fully abstraction and multiple
inheritance in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They
are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of
multiple inheritance.
• It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords
before the interface method and public, static and
final keywords before data members.
In other words, Interface fields are public, static and
final by default, and methods are public and
abstract.
interface printable{
void print();
}
interface Showable{
void show();
}