2. Abstraction
Consider a real-life example of a man driving a car.
The man only knows that, pressing the accelerators will increase the speed of car or applying
brakes will stop the car.
But he does not know about how on pressing the accelerator the speed is actually increasing,
he does not know about the inner mechanism of the car or the implementation of accelerator,
brakes etc in the car.
This is what abstraction is.
3. Abstract Classes and Abstract Methods
In java, Abstraction is achieved by interface or abstract class.
We can achieve 100% of abstraction by using interface.
Abstract class is declared with abstract keywords.
Abstract method is declared without an implementation.
Abstract class may or may not have abstract methods.
4. Abstract Classes and Abstract Methods
Abstract methods can be redefined or can be overriding in subclass.
Any class that contain at least one abstract method means, that class must declared
with abstract keywords.
Can’t access abstract class directly with new operator.
Abstract class can have parameterized constructors and default constructor is always
present in the abstract class.
5. Abstraction Example
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
6. youtube:Zooming | https://github.com/Soba-Arjun/
Advantages of Abstraction
It reduces the complexity of viewing the things.
Avoids code duplication and increases reusability.
Helps to increase security of an application or program as only important details
are provided to the user.