• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing SuperClass static variable in subclass

 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


just wanted to confirm my understanding on how we can access superclass static variable in a subclass.
eg
Class SuperClass
{
static int x =5;
}
Class SubClass extends SuperClass{
//access x from here
}


1. One way is to use the Superclass name eg SuperClass.x

2. access by reference to a superclass instance
eg SuperClass A = new SuperClass();
A.x

3. access by polymorphic instantiation ie
SuperClass A = new SubClass();
A.x

Please correct me if I am wrong and also is there any other way to access x from .....//access here in the above code....

Going crazy with static accesses....Phew...!!

mary
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also you can say 'SubClass.x' because x is static, or just say 'x' because SubClass inherited that variable.
 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,

and please help me with this static acess...

thats one thing I was confused with. I tried to compile this code that accesses the superclass static variable y in the subclass. But code does not compile it gives following error....
super(y) cannot find symbol, variable y
SubClassStatic.y cannot find symbol:variable y

Class CheckStatic{
static int y =2;
CheckStatic(int x) {x=x*2;};

}
public class SubClassStatic
{
SubClassStatic(){super(y);}


public static void main(String[] args){
System.out.println(SubClassStatic.y);
}
 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pplease ignore the above post, i forgot to extend in the subclass
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic