Data hiding in java

 

Introduction

Data Hiding is the key feature of java programming language.Java provides us to hide the variable scopes in classes, data hiding, and method hiding Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through the super keyword which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read. we're going to learn about variables, data, and methods hiding in the Java language.


Let’s understand first “what is hiding”?

Hiding:  “secretly keep somewhere where they cannot be seen or found easily.”

Java gives the freedom to declare variables inside a class, method, block, or constructor. Based on these scopes, Java variable types can be divided into Local Variables, Instance Variables, and Static Variables. 

These variables declared can have different scopes in a program and can be of static or non-static type depending on the place it is declared.

hiding happens when two variables in different type scopes (local and global scopes, parent and child classes) are given the same name. In such cases, the value of the inner scope variable is used because it shadows/hides the value of the outer scope variable.





Variable Hiding

It will happen if we declare a property(attributes) in a local scope having the same name as the one we already have in the outer scope.


Let’s understand based on variable scopes in java.

  1. local variables

  2. static variables

  3. instance variables


local variables

The variables declared in a piece of code such as constructors, and methods in any block of code with curly braces.

Consider the following example, where we declared a message variable with the name message. We may think that the below program throws an error because we declared two variables with the same name message. But fortunately, we will not get any errors, and the output will be “local scope”. Even though both the variables have the same name message, they are declared on different scopes, one in the global scope and the other in the local scope.

We can’t declare local variables as static.

The message variable in global scope is accessible anywhere inside the class whereas the message variable in local scope is accessible only inside the main() method. The output is local scope because of variable shadowing (i.e.) the message variable inside the main() method hides the message global variable and uses its own value.

Sample code


public class LocalVariable {

    private String message = "global scope";             //instance variable

public static void main(String args[])

{

String message=”local scope”;   // local variable

        System.out.println(message);

     }

}


  Output:

                       local scope



static variables

The variables which are declared inside the class but outside methods with the static keyword are those variables we call “static variables”.

Static variables have class-level scope.

Class variables are also called static variables.

Only one copy of the class variable per class regardless of the number of objects created. Class variables are created when the program gets started and destroyed when the program ends. 


Sample code

class StaticScope{

private static String message=” static scope”;

public static void main(String args[])

{

            String message =” local scope”;

                System.out.print( message);                        // local scope

               System.out.print(StaticScope.message);   // hello

}

}

Output              local scope

      hello



instance variables


In superclass and subclass having instance variable of the same name, If you are trying to access by using subclass object, instance variable of the subclass hides the instance variable of superclass irrespective of types. This all process is called field hiding or instance variable hiding.

By using the super keyword we can access the value of the superclass in a subclass.

Non-static hiding happens between two variables

(one in parent class and the other in child class) declared with the same name and not prefixed with the static keyword. 

Non-static variables are called instance variables.


For example

                                   super.variableName;







class Parent {

     String name = "Parent";

    public void displayName() {

         System.out.println(name); }

}

class Child extends Parent {

    String name = "ChildClass";

     @Override

     public void displayName() {

         System.out.println(name); }

}

public class Main {

        public static void main(String[] args) {

              Parent parent = new Parent();

              Child child = new Child();

               parent.displayName();

               child.displayName();   }

}

Output               

                   Parent 

                   Child

Data Hiding


Data hiding is hiding internal data from outside users. The internal data should not go directly that is outside person/classes is not able to access internal data directly. 

It is achieved by using an access specifier- a private modifier.

For data hiding recommended modifier is private.

It is used as security such that no internal data will be accessed without authentication. 

An unauthorized end user will not get access to internal data.

Programmatically we can implement data hiding by declaring data elements as private. Now to access this data or for modification, we have a special method known as getter setter respectively.


Example

class ClassName

{

// private properties

// getters and setters

}


Sample Code


class  Account

{

private BigDecimal balance;

public BigDecimal getBalance(){

if(UserValidation)

{

return balance; 

}

return -1;

// setter method for balance property

}







Method Hiding

 

When a child class defines a static method with the same signature as a static method in the parent class, then the child's method hides the one in the parent class. 



A static method (class method) cannot be overridden in Java. 

But if a static method defined in the parent class is redefined in a child class, the child class’s method hides the method defined in the parent class.

This mechanism is called method hiding in Java. 

In the method hiding concept, the method call depends on the reference type.

known as compile-time polymorphism.

In parent and child class should be declared the same name method with the static keyword.





Sample Code


class  Parent

{

public static void hello()

{

System.out.print(“Parent class”);

}

}



class Child extends Parent

{

public static void hello()

{

System.out.print(“Child class”);

}


}





Test.java


class Test

{

public static void main(String args[])

{

Parent p=new Parent();         // parent class object creation

p.hello();                                 // calling parent class hello method

Child c=new Child();              // Child class object creation

c.hello();                                 // calling child class hello method

Parent p1=new Child();         // assigning child class object parent ref

p1.hello();                           // calling parent class hello method

}

}


Output:

Parent

Child

Parent

Newest
Previous
Next Post »