-1

Here is a simple example where I am inheriting the class property.

class Xyz
{
   int a = 10;
} 

public class Demo extends Xyz
{
   int a = 5;

   public static void main( String[] args )
   {

      Xyz z = new Demo();
      System.out.println(z.a);
   }

}

Since the object is of class Demo is should print 5 but the output is 10. What is the reason behind it?

Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74

3 Answers3

2

For Variables in java , Variables are only accessible using their reference variable not about the object.

Xyz z  // z  is the reference variable of Xyz so it will print 10 instead of 5.



 Xyz z = new Demo(); // override concept only works for Method not for Variables

another confusion may raise of due to overriding. but you should understand that override takes place only in context of Method not for Variables.

So, Be aware your output is Correct. It should be 10 instead of 5.

Thank You

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
0

If you are accesing member variables of an object, you always access the variables of the type the object is declared with.

Comment out int a = 10; in your base class Xyz. Your code won't compile any more...

This is different for methods, which are virtual by default (unless private):

class Xyz
{
    int m()
    {
        return 10;
    }
} 

public class Main extends Xyz
{
   int m()
   {
       return 5;
   }

   public static void main( String[] args )
   {
      Xyz z = new Main();
      System.out.println(z.m());
   }
}

So if you want or even rely on such behaviour as you originally expected, make your member variables private and provide them getters and – if need be – setters (of course, you need to override these in your sub class!).

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

What you really do is creating Xyz Object so the reference to integer a is according to Xyz.

If you want to alter the value of Parent class you should call super access and change parent's value

something like this

class Xyz
{
   int a = 10;
} 

public class Demo extends Xyz
{

   public Demo(){
       super.a = 5;
   }

   public static void main( String[] args )
   {

      Xyz z = new Demo();
      System.out.println(z.a); // 5 is printed
   }

}
kicito
  • 89
  • 4