Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static

 
Raj Neets
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can some please tell me whether
A static variable be inherited or not in the subclass
Thanx you
Raj
 
Sirish Kumar
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Raj,
As per my understanding any member (field or method) is inherited unless it is
1.private in the superclass
2.hidden in the subclass OR
3.overridden in the subclass.
Since fields can only be hidden, the static field is inherited if it has not been declared as private in the superclass and also not hidden by another field with the same name in the subclass
Eg:
class Base
{
private static int i; \\not inherited since it is private
public static int j; \\inherited since it is not private
public static int k; \\not inherited since it has been hidden
}
class Derived extends Base
{
public static int k; \\hides the field with the same name in the superclass
}
Hope that helps.
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ray,
Static variables will be inherited unless
they have a private access modifier.
Maybe the following example can help a little:

As you can see you don't even have to have an instance of
the KidStatic in order to access the static variable.
Greetings,
Gian Franco
[ January 29, 2004: Message edited by: Gian Franco Casula ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic