| Author |
Static and Inheritance
|
Dhandapani Venkataraman
Greenhorn
Joined: Nov 30, 2003
Posts: 10
|
|
Are static methods and Variables,if not private, inherited? If yes, Can they be overridden? What do they mean conceptually ,if they are inherited?
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
They are inherited in the sense that they are in the scope of the subclass -- i.e., a static method Parent.method() can also be called as Child.method(), or just as method() withing the Child class. Variables can not be "overridden," so your second question applies only to methods. Static methods can't be overridden for the simple reason that they're not called polymorphically -- i.e., the compiler decides when compiling the code precisely which static method should be invoked, whereas for non-static methods, of course, that decision isn't made until the program is executed.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
There is an interesting distinction between hiding and overriding. When a child class has an instance method with the same name and signature as a method in its parent class, calling that method on a reference of the parent class's type that happens to point to an object of the child class's type will call the child class's method. This is called overriding and is an example of polymorphism. When a child class has an instance variable with the same name as a variable in its parent class, accessing that variable using a reference of the parent class's type that happens to point to an object of the child class's type will access the parent class's variable. Accessing the same variable using a reference of the child class's type will access the child class's variable. This is called hiding. If static variables and methods of a child class match variables and methods of the parent class, the member selected will be based on the class name used to access that variable or method. Java can't use the actual type of the object because static class members are not part of individual objects. (OK, they are part of the class object, but that's another story.) So all static class members use hiding instead of overriding. [ October 05, 2004: Message edited by: Mike Gershman ]
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
Originally posted by Dhandapani Venkataraman: Are static methods and Variables,if not private, inherited?...
The private-ness is not an issue here. Inheriting and overriding (or hiding) static methods or variables is the same whether they are public, package private, protected, or private. Layne
|
Java API Documentation
The Java Tutorial
|
 |
 |
|
|
subject: Static and Inheritance
|
|
|