19 Abstraction
19 Abstraction
It is the process of hiding the certain details and showing the important
information to the end user called as “Abstraction”.
Example- Real life scenario is car.
How to achieve the Abstraction in java?
There are two ways to achieve the abstraction in java.
1. Abstract class
2. Interface
Abstract class
Note- Multiple inheritances are not allowed in abstract class but allowed in
interfaces
Example-1
package com.abstraction;
}
Note>>
Here, If we declared the method is an abstract then class should be abstract only
as per below example
package com.abstraction;
Example-2- we can write multiple abstract method into abstract class as per
below
package com.abstraction;
We need to create the class which extends from abstract class as shown in
below.
package com.abstraction;
@Override
void a1() {
System.out.println("this is the a1 method..");
}
@Override
void a2() {
System.out.println("this is the a2 method..");
}
package com.abstraction;
public class TestMain {
}
}
Note- Suppose in the sub class, I don’t want to override the abstract methods
then make that subclass as abstract.
Example-1
public interface Student {
Note- if we don’t write public or abstract in interface then JVM will insert it
automatically.
}
Example-3
package com.abstraction;
package com.abstraction;
@Override
public void m1() {
System.out.println("Test-m1 method");
}
package com.abstraction;
Example-4
package com.abstraction;
public interface A {
package com.abstraction;
public interface B {
package com.abstraction;
public interface A {
public abstract void x1(); // allowed
}
package com.abstraction;
public interface B {
public abstract void x1(); // allowed
}
package com.abstraction;
@Override
public void x1() {
System.out.println("Test-x1 method");
}
package com.abstraction;
Output
Test-x1 method
Why interface?
Suppose there is a requirement for Amazon to integrate SBI bank code into
their shopping cart. Their customers want to make payment for products they
purchased.
Let's say SBI develops code like below:
class Transaction {
void withdrawAmt(int amtToWithdraw) {
//logic of withdraw
// SBI DB connection and updating in their DB
}
}
Amazon needs this class so they request SBI bank for the same. The problem
with SBI is that if they give this complete code to amazon they risk exposing
everything of their own database to them as well as their logic, which cause a
security violation.
Now the solution is for SBI to develop an Interface of Transaction class as
shown below:
interface Transaction {
void withdrawAmt(int amtToWithdraw) ;
}
class TransactionalImpl implements Transaction {
void withdrawAmt(int amtToWithdraw) {
//logic of withdraw
//SBI DB connection and updating in their DB
}
}
Now how amazon will do this as below as-
Transaction ti = new TransactionalImpl ();
ti.withdrawAmt(500);
In this case, both applications can achieve their aims.
Difference between Interface and Abstract class: