SEMrush

2 Techniques of Abstraction in Java

Abstract Classes and Methods:  Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details .
While sending an email we create the body of the mail and subject , and the email address to which we want it to be delivered.
We don't exactly know the internal process of how the e-mail is being delivered to the reciever.
Abstraction lets us focus on what the object does instead of how it does it.
Abstract Class
A class that is declared using “abstractkeyword is known as abstract class  
It needs to be extended and its method implemented. It cannot be instantiated.

There are two ways to achieve abstraction in java
  1. Abstract class offers partial (0 to 100%) abstraction
  2. Interface offer (100%) abstraction
It may or may not include abstract methods which means in abstract class you can have concrete methods (methods with body) as well along with abstract methods ( without an implementation, without braces, and followed by a semicolon). 

Example of Abstract class
 // Lines of code below show an abstract class declaration using keyword “abstract”

abstract class MyAbstractClass{
   //line of code below shows an Abstract method: without body and braces
   abstract public void myAbstractMethod(); 

   // lines of code below show a Concrete method: with body and braces
   public void myConcreteMethod(){
      //Write your statements here
   }
}

Note : while declaration of an abstract class
1.    Declare a class as abstract class if it has both abstract methods and concrete methods: If the class is having only abstract methods: declare it as interface.

2.    Declare a class as interface if it has only abstract methods.

Important points
  1. Always declare a class abstract when there is an abstract method inside that class .
  2. An abstract has to be always extended by some other class.
  3. An abstract class may not have any abstract method .
  4. An abstract class can have non-abstract methods (concrete) as well.
  5. non-abstract class will have only non-abstract methods (concrete) .
  6. A non-abstract can NOT have an abstract method

Comments