Abstraction in Java
19:39:00
Abstraction is used to Hiding the complexity and showing the functionality is known as abstraction. Showing the essential data and hiding the non essential data.
Abstract class in Java
A
class that is declared with abstract keyword, is known as abstract class in
java.
It can have abstract and non-abstract methods (method with body).
Before learning
java abstract class, let's understand the abstraction in java first.
Ways to achieve Abstaction..!!
There
are two ways to achieve abstraction in java
1.
Abstract
class (0 to 100%)
2.
Interface
(100%)
Abstract class in Java
A
class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}
|
abstract method
A method that is declared as
abstract and does not have implementation is known as abstract method.
|
Example abstract method
abstract void printStatus();//no body and abstract
|
Example of abstract class that has
abstract method
In
this example, Bike the abstract class that contains only one abstract method
run. It implementation is provided by the Honda class.
1.
abstract class Bike{
2.
abstract void run();
3.
}
4.
class Honda4 extends Bike{
5.
void run(){System.out.println("running safely..");}
6.
public static void main(String args[]){
7.
Bike obj = new Honda4();
8.
obj.run();
9.
}
10.
}
|
running safely.. |
Understanding the real scenario of
abstract class
In
this example, Shape is the abstract class, its implementation is provided by
the Rectangle and Circle classes. Mostly, we don't know about the
implementation class (i.e. hidden to the end user) and object of the
implementation class is provided by the factory
method.
A factory method is the method that returns the
instance of the class. We will learn about the factory method later.
In
this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
1.
abstract class Shape{
2.
abstract void draw();
3.
}
4.
//In real scenario, implementation is provided by others i.e. unknown by end user
5.
class Rectangle extends Shape{
6.
void draw(){System.out.println("drawing rectangle");}
7.
}
8.
class Circle1 extends Shape{
9.
void draw(){System.out.println("drawing circle");}
10.
}
11.
//In real scenario, method is called by programmer or user
12.
class TestAbstraction1{
13.
public static void main(String args[]){
14.
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method
15.
s.draw();
16.
}
17.
}
|
drawing circle |
Another example of abstract class in
java
1.
abstract class Bank{
2.
abstract int getRateOfInterest();
3.
}
4.
class SBI extends Bank{
5.
int getRateOfInterest(){return 7;}
6.
}
7.
class PNB extends Bank{
8.
int getRateOfInterest(){return 8;}
9.
}
10.
11.
class TestBank{
12.
public static void main(String args[]){
13.
Bank b;
14.
b=new SBI();
15.
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16.
b=new PNB();
17.
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18.
}}
|
Rate of Interest is: 7 % Rate of Interest is: 8 % |
Abstract class having constructor,
data member, methods etc.
An
abstract class can have data member, abstract method, method body, constructor
and even main() method.
1.
//example of abstract class that have method body
2.
abstract class Bike{
3.
Bike(){System.out.println("bike is created");}
4.
abstract void run();
5.
void changeGear(){System.out.println("gear changed");}
6.
}
7.
8.
class Honda extends Bike{
9.
void run(){System.out.println("running safely..");}
10.
}
11.
class TestAbstraction2{
12.
public static void main(String args[]){
13.
Bike obj = new Honda();
14.
obj.run();
15.
obj.changeGear();
16.
}
17.
}
|
bike is created running safely.. gear changed |
Interface in java with example programs
Earlier we discussed about abstract class which is used to achieve partial abstraction(hiding irrelevant details from user). In this tutorial we are going to discuss about interfaces, which are used for achieving full abstraction. In this post, we will discuss what is an interface? what is the significance of it? when and how to use it?
What is an interface?
Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. We will discuss these points in detail, later in this post.
What is the use of interfaces?
As mentioned above they are used for abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not support multiple inheritance, using interfaces we can achieve this as a class can implement more than one interfaces, however it cannot extend more than one classes.
Declaration
Interfaces are declared by specifying a keyword “interface”. E.g.:
Interfaces are declared by specifying a keyword “interface”. E.g.:
interface MyInterface { /* All the methods are public abstract by default * Note down that these methods are not having body */ public void method1(); public void method2(); }
Interface Implementation
This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface.
Note: class
Note: class
implements
interface but an interface extends
another interface.interface MyInterface { public void method1(); public void method2(); } class XYZ implements MyInterface { public void method1() { System.out.println("implementation of method1"); } public void method2() { System.out.println("implementation of method2"); } public static void main(String arg[]) { MyInterface obj = new XYZ(); obj. method1(); } }
Output:
implementation of method1
Interface and Inheritance
As discussed above, an interface can not implement another interface. It has to extend the other interface if required. See the below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class implements the Inf2 it has to provide implementation of all the methods of interfaces Inf1 and Inf2.
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 } }
In the program above, “Demo” class is implementing only one interface “Inf2” however it has to provide the implementation of all the methods of interface “Inf1” too, because interface Inf2 extends Inf1
Key points: Here are the key points to remember about interfaces:
1) We can’t instantiate an interface in java.
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.
interface Try { int a=10; public int a=10; public static final int a=10; final int a=10; static int a=0; }
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler will through an error.
interface Try { int x;//Compile-time error }
Above code will throw a compile time error as the value of the variable x is not initialized at the time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final. Here we are implementing the interface “Try” which has a variable x. When we tried to set the value for variable x we got compilation error as the variable x is public static final by default and final variables can not be re-initialized.
class Sample implements Try { public static void main(String args[]) { x=20; //compile time error } }
11) Any interface can extend any interface but cannot implement it. Class implements interface and interface extends interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the method once is enough.
interface A { public void aaa(); } interface B { public void aaa(); } class Central implements A,B { public void aaa() { //Any Code here } public static void main(String args[]) { //Statements } }
14) A class cannot implement two interfaces that have methods with same name but different return type.
interface A { public void aaa(); } interface B { public int aaa(); } class Central implements A,B { public void aaa() // error { } public int aaa() // error { } public static void main(String args[]) { } }
15) Variable names conflicts can be resolved by interface name e.g:
interface A { int x=10; } interface B { int x=100; } class Hello implements A,B { public static void Main(String args[]) { // reference to x is ambiguous both variables are x System.out.println(x); System.out.println(A.x); System.out.println(B.x); } }
Benefits of having interfaces:
Following are the advantages of using 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.
0 comments