I'm trying to understand the concept of abstraction in java. When I came through some tutorials they said that Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.
This is a simple example of how abstract classes are working.
public class Demo {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("woof");
}
}
I understand that though abstract classes we can implement common methods in sub classes like sound() method.
What I don't understand is how that help with data hiding and viewing necessary data only.
Please explain this concept to me.
If you have good example please include that too.
In your example, you create a
Dogand then use it as an animal. In this case, the abstraction is not very useful, because you know that the variableaalways refers to a dog. Now let's say that in some other class you have a methodsoundTwice:Here you don't know what kind of
Animalarefers to, but you can still sound twice.UPDATE
I'm adding this class because the class
Demodoesn't hide much: it needs to know about classDogbecause it creates an instance of it. classOutsideWorldon the other hand doesn't: it only knows about classAnimaland what classAnimalexposes. It doesn't even know that classDogexists.we can now write a class
Catwith a different implementation of methodsound("meow"), and we can still use the samesoundTwicemethod with aCat.We could then rewrite the
Democlass:That would, of course, produce the output: