Abstraction in Java
Abstraction in Java
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 lets you focus on what the object does instead of how it does it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.
Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.
A factory method is a 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.
File: TestAbstraction1.java
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();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Rate of Interest is: 7 %
Rate of Interest is: 8 %
File: TestAbstraction2.java
Rule: 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.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I am a
I am b
I am c
I am d