javaoopabstractiondata-hiding

Abstraction and Data Hiding in java



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.


Solution

  • In your example, you create a Dog and then use it as an animal. In this case, the abstraction is not very useful, because you know that the variable a always refers to a dog. Now let's say that in some other class you have a method soundTwice:

    class OutsideWorld {
        static void soundTwice(Animal a) {
            a.sound();
            a.sound();
        }
    }
    

    Here you don't know what kind of Animal a refers to, but you can still sound twice.

    UPDATE

    I'm adding this class because the class Demo doesn't hide much: it needs to know about class Dog because it creates an instance of it. class OutsideWorld on the other hand doesn't: it only knows about class Animal and what class Animal exposes. It doesn't even know that class Dog exists.

    we can now write a class Cat with a different implementation of method sound ("meow"), and we can still use the same soundTwice method with a Cat.

    We could then rewrite the Demo class:

    public class Demo {
        public static void main(String[] args) {
            Animal a = new Dog();
            OutsideWorld.soundTwice(a);
            a = new Cat();
            OutsideWorld.soundTwice(a);
        }
    }
    

    That would, of course, produce the output:

    woof
    woof
    meow
    meow