Dil.
Dil.

Reputation: 2076

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.

Upvotes: 3

Views: 4195

Answers (5)

Jayanth
Jayanth

Reputation: 816

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;
    }

}

Upvotes: 1

Abhi
Abhi

Reputation: 1005

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 :)

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 9651

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

Upvotes: 1

Wall
Wall

Reputation: 88

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.

Upvotes: 0

Yati Sawhney
Yati Sawhney

Reputation: 1402

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.

Upvotes: 1

Related Questions