• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding variables??

 
Ruchi Gupta
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have noticed that methods get overriden but the variables do not specially when i equate asuper class to a sub class why does this happen.
taking for eg.
class Base
{
int i=23;
void show()
{
System.out.println("from super");
}
}
class Sub extends Base
{
int i = 34;
Sub(){}
void show()
{
System.out.println("from sub");
}
}

class testoverride
{
public static void main(String[] as)
{
Sub s= new Sub();
Base b = new Base();

b=s;
b.show();
System.out.println(b.i);
}
}
the result is
from sub
23//not 34
why is not the variable of the sub class getting called??
please help me with this
ruchi
 
Thillai Sakthi
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here what you have done is,
1. Created objects for sub class and super class.
2. And assigning the sub class object ref to super class object reference.
When you are doing like this,the super class object ref will have access to all the methods in super class which are not overridden by sub class and methods of the super class for which implementation has been provided by the subclass(basically u have overrided them).As the variables are not overridden(how can we do such a thing?!)when u try to access the variables of the super class(in this case b.i)you get only the super class fields only.
Another way to approach this is as the fields (class level instance variables) belong to a particular class and objects also typically "belong" to a particular class such fields can be accessed by those objects.
hope this clarifies.
MK
 
Ruchi Gupta
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello MK,
thanks, i understood it but actually i wanted to know why doesn't variables get overriden as methods do.
ruchi
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi gupta!
the concept of overriding come in case of functionality.for methods,by overriding them we are changing the functionality of the methods.in case of variables,there is no concept of functionality.they can just hold some values.so there is no question of functionality.but variables will have values, which we can change.
i hope i could answer your question.bye
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic