Field Hiding and Method Overriding

The topic for today is to discuss what are field hiding and Method Overriding in Java.

 

 

MENU

 

1) Artificial Project 1 Uninformed and Informed Search Algorithms.

2) Artificial Intelligence Project on Alpha Beta Pruning.

3) Artificial Intelligence

4) Computer Security ( Bell LaPadula Model)

5) Explicit and Implicit DLL Linking

6) Fun With Pointers in C++

7) Mathematical Software plotting in maple and matlab coming soon

8) Requirements

9) Shell Scripting with Linux/Unix 

10) VirtualFunctions C++

11) Critical Essay and Analysis Part 1.

12) Critical Essay and Analysis Part 2

13) Here are some interesting Probability and Random Processes course problems.

 

 

When does Field Hiding occur?

Consider you have two classes. One is Base and the other is inherited from Base called Derived. Base has a public string field called 'myName' and the Derived declares a private string field called 'myName'.

Now in the client code, there is a code with the following line.

System.

out.println(new Derived().myName);

The important point to understand here is that the field myName in the Base class has not been overridden. The field has simply been hidden. The above code will give a compilation error because, myName in the Derived class is declared as private and hence cannot be accessed. So the question is, can I still access the hidden field directly from the instance of the subclass? Yes you can.

Simply cast the Derived instance back to Base and call myName.

The complete code for this is:

class

Base {

public String myName = "Base";

public int add()

{

return 1;

}

}

 

 

class

Derived extends Base {

public String myName = "Derived";

public int add()

{

return 2;

}

}

public

class tryMe {

/**

* @param args

*/

public static void main(String[] args)

{

System.

out.println(((Base)new Derived()).add());

//method overriding, prints 2

System.out.println(((Base)new Derived()).myName);

//field hiding,   prints Base.

}

}

 

The code above, also highlights what method overriding is and a very important difference between method overriding and field hiding.

When the add() method is overridden, you cant invoke the add() method of the base class directly from the instance of the subclass, unless you call the super() from the subclass function. But in field hiding, you can call the base class field by simply casting the derived object as Base as seen in the above code.