Abstraction
In Java, the process of hiding the intricate code implementation details from the user is done by the abstract class. It just provides the user with the necessary information. This process is known Data Abstraction in OOP. Abstract class is a template that stores the data members and methods that we use in a program. Abstract classes cannot be instantiated directly.
Data Abstraction is also the process of identifying only the required qualities of an object while discarding the extraneous aspects.
The features and behaviors of an object assist to distinguish it from other things of the same sort, as well as classify and group them. Interfaces and abstract classes are used to achieve abstraction in Java. Using interfaces, we can accomplish complete abstraction.
Advantages of Abstraction
- It simplifies the process of seeing things.
- Reduces duplication of code and improves reusability.
- Only important details are shown to the user, which helps to increase the security of an application or software.
Key points to know about abstract class and methods in Java:
- An abstract class has the abstract keyword in its name.
- The term "abstract method" refers to a method that is declared but not implemented.
- All abstract methods may or may not be present in an abstract class. Some of these could be concrete procedures.
- A method that is specified as abstract must always be redefined in the subclass, forcing overriding OR making the subclass abstract.
- Any class with one or more abstract methods must also have the abstract keyword specified.
- An abstract class can't have any objects. An abstract class, on the other hand, cannot be directly instantiated with the new operator.
- An abstract class can have parameterized constructors, but it will always have a default function Object() { [native code] }.
Example No.1:
Com.knowledge2life
abstract class Website{
abstract void run();
}
class Net extends Website{
void run(){System.out.println("Knowledge2life");}
public static void main(String args[]){
Website obj = new Net();
obj.run();
}
}
OUTPUT:
Example No.2:
Com.knowledge2life
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("Knowledge2life");}
}
class Circle1 extends Shape{
void draw(){System.out.println("Programming Knowledge2life");}
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}
OUTPUT:
Programming Knowledge2life