3


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.

Dil.
  • 1,996
  • 7
  • 41
  • 68
  • 2
    its not about data hiding (its known as encapsulation). It's actually your clients depends on abstraction (or interface) rather than worrying about its implementation which you can plug at any point in time with multiple at runtime – SMA Feb 15 '18 at 11:18
  • @SMA so the relevant data that you are hiding is Dog class or other implementation and unnecessary data are like abstract class or interface? How is that possible. Please explain more. – Dil. Feb 15 '18 at 11:30

5 Answers5

1

Abstraction in Java is not different then what we use in Software engineering terms.

Abstraction generally answers to WHAT part of your problem statement.

  • What all operations a system will support?

  • What is the system meant for?

Think about the abstract datatypes: Example Stack

All you care about is

  1. pop() --> return you the top element
  2. push() --> adds the element

You simply don't care about the implementation details. So your java classes are abstracted in the same way.

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19
  • So you are saying the person calles Animal a = new Dog(); a.sound(); doesn't know about how sound() method operates in Dog class. Purpose of abstraction is hide that information – Dil. Feb 15 '18 at 12:25
1

Abstraction is not just about showing only “relevant” data and “hide” unnecessary details of an object from the user.

Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.

In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

The one you are explaining in your example is one just form of it.

In your example of Animal class, if sound() method is not an abstract one and you have some random abstract method in that class, imagine a case someone wrote the Animal class and you are extending it in Dog class. Irrespective of the implementation in Actual Animal class, you can write the code in your current class.

Imagine the you haven't overriden the sound() method in Dog class, still if you call `

Dog d= new Dog(); d.sound();

` will get you the code of Animal sound().[Given: sound() method is not abstract]. The code of Animal class would be executed. Dog object does not even know what the sound() method has in it...but it is still able to make use of it. This process of not knowing but making use of something is what abstraction actually is

As mentioned by Yati Sawhney, pop() and push() methods are quite good examples.

Else,

you can have hascode() and equals() method from Object class, where no one knows how the calculation is done but you end up with a number and comparing the references respectively.

Data Hiding/Encapsulation:

Data hiding is not same as Abstraction. Not to confuse one with the other.

Abstraction is hiding the code implementation from other Object/user whereas Data hiding is achieved by Encapsulation via POJO classes.

Data hiding has to do with the instance variables which decides the state of the Object. Hiding its content using the setter() and Getter() methods is Data Hiding/ Encapsulation.

You may wonder, how a getter() method is hiding the data whereas it just returns the data we requested but there is an untold story about the getter/setter methods.

Example: Refer the getName() method from the below code

public class Person  {


    private  int age;
    private  String name;



    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
       // can restrict the code without displaying data to user
         if(condition)//restricted user check
            return null;//returning null because the user is not supposed to view the data

        return name;
    }

}
Jayanth
  • 746
  • 6
  • 17
  • So as you say, the Demo class that has main method shows only Animal a = new Dog(); a.sound();. Nothing else about the process of Dog class. Thats purpose of abstraction. Is that what are saying? – Dil. Feb 15 '18 at 12:16
  • No. Imagine the you have not overriden the sound() method in Dog class, still if you call Dog d= new Dog(); d.sound(); will get you the code of Animal sound().[Given: sound() method is not abstract]. The code of Animal class would be executed. Dog object does not even know what the sound() method has in it...but it is still able to make use of it. This process of not knowing but making use of something is what abstraction actually is. let me know, if this is not clear!! – Jayanth Feb 15 '18 at 13:01
1

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
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • So as you say by hiding what kind of class Animal is, we can hide unnecessary data. is that what you are saying? Please explain. – Dil. Feb 15 '18 at 12:12
  • @pippilongstocking more precisely, that in this method, we don't know anything about the actual animal, except what class `Animal` exposes (method `sound`) – Maurice Perry Feb 15 '18 at 12:15
  • So we are not hiding the information about dog class we are hiding the information about abstract class. Is that correct? – Dil. Feb 15 '18 at 12:17
  • @pippilongstocking aheum... the opposite is true – Maurice Perry Feb 15 '18 at 12:18
  • @pippilongstocking this method `soundTwice` doesn't know anything about class Dog; it doesn't event know that class `Dog` exists. – Maurice Perry Feb 15 '18 at 12:19
  • @pippilongstocking but it must be aware of class `Animal` because it uses method `sound`. – Maurice Perry Feb 15 '18 at 12:20
  • Hahaha that what I'm trying to figure.. if we hide information about the Dog class's method information or any class that extends Animal class.. What happened when we create the main method in Dog class itself and implemented the methods Animal a = new Dog(); a.sound(); – Dil. Feb 15 '18 at 12:21
  • @pippilongstocking what's the difference? (with having the main method in the Demo class) – Maurice Perry Feb 15 '18 at 12:23
  • @pippilongstocking the thing is: where we are creating an objet, we must know the actual class of the object (unless we're using reflection) – Maurice Perry Feb 15 '18 at 12:25
  • @pippilongstocking but we can now write a class `Cat` with a different method `sound` ("meow"), and we can still use the same `soundTwice` method with cat. – Maurice Perry Feb 15 '18 at 12:27
  • And are you implementing soundTwice in Demo class? as a static method? – Dil. Feb 15 '18 at 12:29
  • For my understanding the purpose here is to hide the implementation of abstract method in abstract class (sound implementation is Dog class) from outside world, which is demo class. Nothing else right? – Dil. Feb 15 '18 at 12:31
  • @pippilongstocking no: it's not the `Demo` class because the `Demo` class must know about the `Dog` class because it creates (instanciates) the `Dog`. The outside world would be the class in which the `soundTwice` method would be declare. This class doesn't exist in your example. – Maurice Perry Feb 15 '18 at 12:40
  • @pippilongstocking I'm claiming that your example is a bad example. Add this other class to it, and it would be much better. – Maurice Perry Feb 15 '18 at 12:41
  • Can you edit your answer with the changes please? then I can understand better. Please. – Dil. Feb 15 '18 at 12:43
0

Abstraction means - not providing/having the implementation details. Imagine you are the authority to decide on what parts a Car must have. You will list those functionalities as abstract methods.

Later you will share this (contract) abstract template to Hundai, Ford etc to have their own implementation to make a complete Car.

Wall
  • 88
  • 1
  • 9
0

Abstraction

Ways to achieve Abstraction There are two ways to achieve abstraction in java

  1. Abstract class (0 to 100%)
  2. Interface (100%)

Basic Knowledge about : Abstract Methods and Classes

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

    public abstract class ClassName{
       // declare fields
      // declare nonabstract methods
      abstract void methodName();
    }

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void methodName(Parameter List);

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Understanding the real scenario of abstract class:

Consider a situation of making a function to get student strength of any school.

Now we will create an abstract class and abstract function getStrength().

Then every school (Govt or private) can use this abstract method and provide implementation.

//Consider this Code


package stackoverflow;

abstract class StudentStrength {

    abstract int getStrength();
}

class GovtSchool extends StudentStrength {

    @Override
    int getStrength() {
        return 100;

    }
}

class PrivateSchool extends StudentStrength {

    @Override
    int getStrength() {
        return 200;

    }
}

public class GetInfo {
    public static void main(String args[]) {

        StudentStrength ss;

        // referring abstract class and creating object of child class
        ss = new GovtSchool();
        System.out.println("Student strength in Govt School : "+ ss.getStrength());
        // output of above : 100
        ss = new PrivateSchool();
        System.out.println("Student strength in Private School : "+ ss.getStrength());
        // output of above : 200
    }
}

Explanation:

In this example, StudentStrength is the abstract class, its implementation is provided by the GovtSchool and PrivateSchool classes.

Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.

In this example, if you create the instance of GovtSchool class, getStrength() method of GovtSchool class will be invoked.

File: GetInfo.java

Student strength in Govt School : 100 Student strength in Private School : 200

ANSWER TO: What I don't understand is how that help with data hiding and viewing necessary data only.

Like demonstrated in the above code, we are referring the abstract class and using the functionality of the child class hiding the working of child class from the end user.

I hope I was helpful :)

Abhi
  • 995
  • 1
  • 8
  • 12