Calling static method from a (superclass) list of subclass instances - java

Say I have a base class A (with a virtual method called normalInit()), and 300 subclasses: A1, A2, A3, ... Each of these subclasses have a staticInit() static method, plus a normalInit() override. (Please don't ask why; this is in a production software, already given, can't change the design for better reuse. Actually, those subclasses are generated by a code generator, but this is irrelevant now.)
Depending on the different executions of the application, a (small) subset of A1, A2, A3, ... needs to be initialized. In other words, there are some data that all instances of a particular Ai share or access commonly. Obviously, it is reasonable to define and treat these entities as static members/methods (as they are shared by all instances of an Ai).
So how to initialize the statics (and call the static methods) of this subset?
To be brief, it's not a solution to static-initialize all Ai subclasses, because only a small subset will be required (would be a waste of memory). The static behavior in Java apparently gives a solution to this: the static initializers of a class are initialized when a class is accessed for the first time (I disregard some special cases here, e.g. compiler inline of pritimive final statics, as in that case, technically there is no class access, just on source code level).
The problem is, I need deterministic (actually at-predefined-time) static initialization, because their static behavior also accesses the current static (global) state of the application. So static initializers are not an option, I need static methods, to call them explicitly at the appropriate place.
In the application in question, this must be done when instances of various Ai classes are accessed via iterating through an ArrayList<A>, where A is the superclass.
for (int i = 0; i < list.size(); ++i) {
list[i].normalInit(args); // normalInit() is an instance method
}
This list consists of Ai instances (e.g. 950 instances of A1, 1750 instances of A2, etc., in an unsorted, "random" order).
In other words, I don't have access to concrete class names (so I can't just call A4.staticInit()), because I don't know which Ai has instances in the list. Note that I know statics are bound at compile time and I do know that polymorphism is not possible here, so I'm not asking how to call the static methods from the above loop! The concretely called instance (and thus its Class) is decided at runtime, due to dynamic dispatch, when normalInit() is called.
An apparent solution is to call the concrete class' staticInit() method from the normalInit() override:
public class A2 {
#Override
public void normalInit(int[] args) {
// ...
staticInit();
}
private static void staticInit() {
if (!sStaticInitialized) {
sStaticInitialized = true;
...
}
}
}
For this, the code generator templates that generate the Ai subclasses must be modified.
But this (and the above code) doesn't look like a nice solution. I understand if the overall app design is somewhat flawed, but even if that's your viewpoint, I would grateful if such claims are augmented with additional (independent) constructive advice. Is there a nicer solution/idiom to the above issue?

Ok, answering it using reflection:
String classPrefixName = "com.your.company.A";
for (int i = 0; i< 300; i++) {
Class<?> clazz = Class.forName(classPrefixName+i); //look for the class
Method method = clazz.getDeclaredMethod("staticInit"); //look for the method
method.invoke(null); //invoke(null), since it's a static method
}
That way you don't need to wrap the static method inside an instance one.

Related

Is it necessary for instance methods to access instance variable in java?

public class Main {
void sum(int a, int b) {
int c = a + b;
System.out.println(c);
}
public static void main(String args[]) {
Main ob = new Main();
ob.sum(10, 125);
}
}
In the above code there is no instance variable, but I have read that if a method is an instance method it should access instance variable. So is 'sum' an instance method?
sum is an instance method here, because it's not static and requires an instance of the object. You create your instance here:
Main ob = new Main();
In this particular case sum could indeed be made static, slightly simplifying the code by not requiring an instance.
I have read that if a method is an instance method it should access instance variable
I suspect what you were reading is suggesting that if a method doesn't interact with the instance at all then it probably should be static. There may be mention of the term "pure function" in the text somewhere.
I wouldn't go so far as to say that all potentially static methods everywhere should be made static as a universal rule. It really comes down to the semantics of the object itself. Since the object you have here has very little semantic context, this one tiny example could easily go either way.
But suppose you expanded your object to also include methods for subtract, multiply, divide, etc. As the object expands, suppose one or more of those additional methods did use instance variables. It would be a jarring experience to have an object with multiple semantically-similar methods, some of which are static and some of which are not.
Rather than focus on any particular rule that someone gives you, focus on what you are intending to build as your object. If you think that it should be static, make it as such. If you feel that it shouldn't, then don't. If you're unsure, then as an exercise implement both and see which you prefer in that particular case.
Looking to the future plans for what you're intending to build is important, because the more code you have relying on your object throughout the application the harder it will be to change from static to instance or vice-versa.
Yes, 'sum' an instance method because any non-static method is an instance method.
Moreover, It is not necessary that an instance method should access instance variable.
The correct statement is "if a method is an instance method it can access instance variable.

Thinking in OOP way

Whenever I think that I am gaining some confidence in OOP then suddenly I get bitten by some advance example. Like in this very great article by Uncle Bob he uses the below class an example for his kata.
public class WordWrapper {
private int length;
public WordWrapper(int length) {
this.length = length;
}
public static String wrap(String s, int length) {
return new WordWrapper(length).wrap(s);
}
public String wrap(String s) {
if (length < 1)
throw new InvalidArgument();
if (s == null)
return "";
if (s.length() <= length)
return s;
else {
int space = s.indexOf(" ");
if (space >= 0)
return breakBetween(s, space, space + 1);
else
return breakBetween(s, length, length);
}
}
private String breakBetween(String s, int start, int end) {
return s.substring(0, start) +
"\n" +
wrap(s.substring(end), length);
}
public static class InvalidArgument extends RuntimeException {
}
}
I have following doubts:
Why the static helper method wrap?
Why the InvalidArgument class is nested and static?
Why do we even need to initialize this class since its nothing but an algorithm and can operate without any instance variable, why we need ~100 instances(for eg) of it?
Why the static helper method wrap?
There is no especially good reason - I think that it is a subjective judgement that:
WordWrapper.wrap("foo", 5);
is neater than
new WordWrapper(5).wrap("foo");
(which I would agree it is). I tend to find myself adding methods like this when the code just feels very repetitive.
However, the static form can lead to hidden problems: invoking that in a loop results in the creation of a lot of unnecessary instances of WordWrapper, whereas the non-static form just creates one and reuses it.
Why the InvalidArgument class is nested and static?
The implication of it being nested is that it is only for use in reporting invalid arguments of methods in WordWrapper. For instance, it wouldn't make much sense if some database-related class threw an instance of WordWrapper.InvalidArgument.
Remember that you can reference it as InvalidArgument for convenience if appropriately imported; you're still always using some.packagename.WordWrapper.InvalidArgument, so its use in other classes doesn't make semantic sense.
If you expect to use it in other classes, it should not be nested.
As for why static: there are two reasons that I can think of (which are sort of different sides of the same coin):
It doesn't need to be non-static. A non-static nested class is called an inner class. It is related to the instance of the containing class which created it; in some way, the data in the inner class is related to the data in the outer class.
What this actually means is there is a hidden reference to the outer class passed into the inner class when it is created. If you never need to refer to this instance, make it static, so the reference isn't passed. It's just like removing unused parameters of methods: if you don't need it, don't pass it.
Holding this reference has unexpected consequences. (I draw this as a separate point because whereas the previous one refers to a logical requirement/design for the reference or not, this refers to practical implications of holding that reference).
Just as with holding any reference, if you have a reference to an instance of the inner class, you make everything that it references ineligible for garbage collection, since it is still reachable. Depending upon how you use instances of the inner class, this can lead to a memory leak. The static version of the class doesn't suffer from this problem, since there is no reference: you can have a reference to a InvalidArgument when all of the instances of Wrapper are cleared up.
Another consequence is that the contract of InvalidArgument is invalid: Throwable, a superclass of InvalidArgument, implements Serializable, meaning that InvalidArgument also implements Serializable. However, WordWrapper is not Serializable. As such, serialization of a non-static InvalidArgument would fail because of the non-null reference to WordWrapper.
The simple solution to both of these issues is to make the nested class static; as a defensive strategy, one should make all nested classes static, unless you really need them not to be.
Why do we even need to initialize this class since its nothing but an algorithm...
Good question. This is sort of related to your first question: you could get away with just the static helper method, and remove the instance methods and state.
Before you chuck away your instance methods, there are advantages to instance methods over static methods.
The obvious one is that you are able to store state in the instances, for instance length. This allows you to pass fewer parameters to wrap, which might make the code less repetitive; I suppose it gives an effect a bit like partial evaluation. (You can store state in static variables too, but global mutable state is a royal PITA; that's another story).
Static methods are a tight coupling: the class using WordWrapper is tightly bound to a specific implementation of word wrapping.
For many purposes, one implementation might be fine. However, there is almost always a case for at least two implementations (your production and test implementations).
So, whereas the following is tightly bound to one implementation:
void doStuffWithAString(String s) {
// Do something....
WordWrapper.wrap(s, 100);
// Do something else ....
}
the following can have an implementation provided at runtime:
void doStuffWithAString(WordWrapper wrapper, String s) {
// Do something....
wrapper.wrap(s);
// Do something else ....
}
which is using the wrapper as a strategy.
Now, you can select the word wrapping algorithm used for a particular case (e.g. one algorithm works well for English, but another works better for Chinese - maybe, I don't know, it's just an example).
Or, for a test, you can inject a mocked instance for tests which just returns the parameter - this allows you to test doStuffWithAString without testing the implementation of WordWrapper at the same time.
But, with flexibility comes overhead. The static method is more concise. For very simple methods, static could well be the way to go; as the method gets more complicated (and, particularly in the testing case, it becomes harder and harder to work out the input to provide to get a specific output which is important to your test case), the instance method form becomes a better choice.
Ultimately, there is no hard-and-fast rule for which to use. Be aware of both, and notice which works best in given situations.

Java Static vs Instance

So my coder friend hates using the static coding. Yet my Java program is full of it to link between classes, and I have a lot of them!
Is it worth rewriting the whole code to remove the static method?
Is there any advantage of using one over the other?
1. An instance variable is one per Object, every object has its own copy of instance variable.
Eg:
public class Test{
int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have its own copy of x.
2. A static variable is one per Class, every object of that class shares the same Static variable.
Eg:
public class Test{
public static int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have the exactly one x to share between them.
3. A static variable is initialized when the JVM loads the class.
4. A static method cannot access Non-static variable or method.
5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.
static is for the cases where you don't want to have copy for each instance
instance variables are for the cases where you want separate copy for each instance of object.
Based on business cases, which one to use may change.
If you have too many static functions and variables it can lead to a more functional approach rather than true OO. Also if you have public static variable then you replicate global variable which are not good. Keeping track of them is a nightmare.
Generally my rule is to use instance variables if you can and only have static variables and functions if it really is generic over a class rather than an object
This is quite a good answer to a similar questions
Java: when to use static methods
Rather than just linking to methods consider using the new operation to create a new object and access the method from that in a non static way.
before
public void myMethod(){
Time.setTime(Time.getTime() + 20);
System.out.println(Time.getTime());
}
after
public void myMethod(){
Time t = new Time();
t.setTime(t.getTime() + 20);
System.out.println(t.getTime());
}
Any state that is held in these methods will now be the to instance of time you have created. You could also share the variable t accross other methods if you needed to.
Garbage Collection - static fields live much longer then instance fields.
From a logic point of view, static fields are ONLy suppose to be shared among every single instance - if it is truly your case then no problem of course.
Are you talking about static methods or static properties?
As far as static methods are concerned, there is only one way to abuse them, and that is when you define methods that take an object instance as a parameter. You should never need to do that and in my view doing so is poor coding practice. Here is an example:
static int add(ThisClass a, ThisClass b) {
return a.value + b.value;
}
If you are talking about static variables in the class, you are basically into the subject of "singletons" which is where there is intended to be only one instance of a particular class. Singletons are subject to a lot of abuse. They are used by many class libraries (think JDNI and the logging classes) but if an application makes extensive use of them it can be a sign of a poorly structured program. That is probably what your friend is bitching about.
Instance and Static variable:
Answer to your Question: I would say it is worth to use static variable to save memory allocation.
Memory allocation:
For static variable only one memory location is allocated irespective to no of object created and for Instance variable each object one memory location allocated
Now consider this example, consider you are working on companies internal project where you have to create 1M object to Employee class and some property to the Employee class are eid, ename, ecompany now Important thing is that all employees are working in XYZ company so value to the property ecompany is gonna be "XYZ" irrespective of Employee.
Now you know the situation, value to the property ecompany is gonna be XYZ for 1 Million Object.
Now you decide you want to declare ecomapny property as static or instance considering memory allocation
if you declare it as a static then minimum memory allocated to ecompany will be only 48 bytes which very less compare to memory needed to store 1 Million instance variable. 100000 * 48 bytes = 48 Million bytes.
When you use static objects (except for the case of singleton) you're actually implementing functional programming combined with global variables. If you do that a lot - you should reconsider either your design or using Java (maybe you should use a functional programing language such as list, scheme etc).
Pro Static
Once a static member is called from the inside or the outside of the class, then the static constructor of the class is called. The "static object" will live through the whole session, hence you will win in performance.
Con Static
Static members cannot have states, hence they cannot talk to non-static members of the class.
Example
If we consider the BigInteger class, this class would gain if some of the parts were made into static members.
An instance of the class represent (as expected) a big integer.
However, the main methods add and multiply are not static (which they should be in a better world), which is bad for performance.
Hence, in practice one should not be afraid of mixes between static and non-static.
I don't like using static variables or methods because they have no real inheritance. This makes it more difficult to mock for testing. Using instances gives you the flexibility of full polymorphism. On the other hand, sometimes static variables are necessary, for example with a global cache. Static methods can be a benefit if they provide helper methods for classes/objects/primitives which you cannot access or extend. These helper methods are so simple they don't need inheritance. For example java.util.Arrays class or java.util.Collections.

Java Variables Basics

Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.
I need some help understanding setting up variables and why I should do it a certain way.
Here is an example of my variables list for a class:
Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
String pageContent = null;
String pageName = "http://www.shanescode.com";
DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;
So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?
Thanks for your help and please don't be too harsh. I just need some clarification.
These words all alter the way the variable to which they are applied can be used in code.
static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.
public class MyClass{
public static int myNumber;
}
In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.
final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:
public final int myNumber = 3;
or as part of the class's constructor:
public MyClass(int number){
this.myNumber = 3;
Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.
private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:
public class MyClass{
private int myNumber;
public void changeNumber(int number){
this.myNumber = number; //this works
}
}
MyClass myInstance = new MyClass();
myInstance.myNumber = 3; //This does not work
myInstance.changeNumber(3) //This works
Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.
static = same for all instances of a class.
final = unchanging (reference) for a particular instance.
If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.
If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.
A search for "java final static" gives pretty useful further reference on the use of those keywords.
The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.
Private
The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."
Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.
Static
The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.
Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.
An example:
public class Cat {
public static void speak() { System.out.println("meow"); }
}
public class Lion extends Cat {
public static void speak() { System.out.println("ROAR"); }
}
// ...
public static void main(String argv[]) {
Cat c = new Lion();
c.speak();
}
The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.
Another thing that might trip you up is this:
Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.
So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.
I don't know why you would make anything private.
Folks will chime in and say that private is a Very Important Thing.
Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.
If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.
Otherwise, if you're not selling it, don't waste a lot of time on private.
Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.
One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.
To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,
private int someNumber;
This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:
public int getSomeNumber()
{
return someNumber;
}
Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:
public void setSomeNumber( int someNumber )
{
this.someNumber = someNumber;
}
Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!
Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...
static int classVariable = 0;
the variable can be accessed without a class instance. For example, you might see this done from time to time:
public static final int MY_CONSTANT = 1;
While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:
myInstance.setSomeNumber( MyClass.MY_CONSTANT );
java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.
Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.
If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.

Inheritance vs Static in Java

I dont quite understand why Static methods can be inherited in Java ?
Inheritance is like inheriting from the base class AND Static belongs to the Class and not Object.
So if the Static belongs to the Class only why does it trickle down to the derived class ?
Shouldn't it just stay with the Class in which it was defined ?
Is Inheriting Static methods a good programming practise ?
In java static methods are not inherited (or the right word is overridden) but they can be hidden.
The big different here is that they are not subjected to polymorphism as object method are.
public class C1 {
static public void M1() {
System.out.println("C1.M1().");
}
static public void main(String ... Args) {
M1();
}
}
public class C2 extends C1 {
static public void M1() {
System.out.println("C2.M1().");
}
static public void main(String ... Args) {
M1();
C1.main(Args);
}
}
When run C2.main(null), you will get:
C2.M1().
C1.M1().
As you can see,
calling M1() in C1.main(...) refer to M1 of C1 and
calling M1() in C2.main(...) refer to M1 of C2.
The invocation of M1 (with out any prefix, see the first line of each main()), are not subjected to polymorphism as M1 in C1 does not get overrided by C2.
But calling from C2 refer to M1 of C2 as M1 of C2 is hide the one in C1.
Read more here.
EDIT: I've just re-read your question and just see the part about "good programming practise".
As I said, static method are not inherited but hidden so they are as good as different method.
From a code's point of view, they are completely different methods.
Let say.
C1 has static method M1.
C2 extends C1 and has static method M1.
C3 extends C2.
When call M1 (without prefix) from C1, you call C1.M1().
When call M1 (without prefix) from C2, you call C2.M1(). // derive but get hidden
When call M1 (without prefix) from C3, you call C3.M1(). // derive and no hidden
To specify which method, use class name like C1.M1(), C2.M1() and C3.M1() (this will called C2.M1()).
So this implementation allows static method to be reimplemented but only as a different method not as an overridden (or replacement) method.
Therefore, this usually no different from let say naming them differently like: C1_M() and C2_M().
So you may ask, why bother having this feature? I don't really know. Perhaps allows a more flexible naming to method.
But there is usage (that might or might not be intented) that I used is polymorphism via reflection.
Since you can get and call a method by name using reflection, allowsing them to have a same name will enable polymorphism when do via reflection.
For example (rought code, may not run):
String aClsName = "C1"; // "C2";
Class aCls = Class.forName(aClsName);
Method aMth = aCls.getMethod("M1"); // M1 of C1 or C2 depends on the class name.
aMth.invoke(null);
OR
Object aObj = new C1(); // new C2();
Class aCls = aObj.getClass();
Method aMth = aCls.getMethod("M1"); // M1 of C1 or C2 depends on the class of the object.
aMth.invoke(null);
When think about it, I think Java has use this too (like, writeObject(...) for serialization) so it may be intented.
So to conclude, hiding static method is not a good programming practice (Eclipse also recommend against it) but it can be useful in two cases, (1) to name the method exact what it suppose to do and (2) to polymorph it using reflection.
Hope this helps.
I dont quite understand why Static
methods can be inherited in Java ?
The short answer is that statics are NOT inherited in Java. Rather, the static members declared in a class are (subject to "access" restrictions) directly visible in the namespace of derived classes, unless they "hidden" by declarations in the derived class.
So if the Static belongs to the Class
only why does it trickle down to the
derived class ? Shouldn't it just stay
with the Class in which it was defined
?
Trickle down is not a technical term. But that's not what is happening anyway. The static members of the class are not members of the derived class.
Is Inheriting Static methods a good
programming practise ?
You cannot stop it happening!
Just FYI, here are some "good practice" issues related to statics:
Mutable static attributes should be private, and preferably recast as Singleton objects.
A lot of statics members (methods or attributes) or even Singletons, can be a sign of a bad design. It is certainly not "the object-oriented way".
In some kinds of application (e.g. web apps), even Singleton objects are problematic.
It is bad practice to refer to a static method a obj.someStaticMethod() or this.someStaticMethod(). Either qualify the static name with the class name, or refer to it without qualification.
It is (arguably) better to qualify a reference to a static in superclass; e.g. in SubClass, refer to SuperClass.someStaticMethod() rather than someStaticMethod(). (But the downside is that the code is more verbose. This falls under the same banner as the pros and cons of importing.)
static final constants should be declared with all-caps names.
As you state, the static method belongs to the class and since inheritance describes a IS-A relationship between types does it not stand to reason that a subclass would inherit all of the members of its superclass?
I personally think this implementation makes a lot of sense!
For method invocation using inheritance to take place, you need to have one instance of the class.
Since static method do not have an instance, the method definition is attached to the class it self ( no dynamic dispatch )
That's more or less the rationale in my own words.
It is more a technical problem ( with the implementation ) than a language feature.
As for:
Is Inheriting Static methods a good programming practise ?
No, it is not. This is hard specially when you come from an structured programming language, eventually it would make sense.
I don't really use much static methods in first place.
public class StaticTest extends StaticBase {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Start");
StaticTest.printIt();
}
}
class StaticBase{
public static void printIt(){
System.out.println("Inside bas Class");
}
}
Does this code not prove that Static is Inherited ??
If B is a subclass of A and we have A a = new B(); as a legal statement hence they are the same type and if the static method is on A then B will have it since they are of the same type in that regard. I think your confusion lies with the fact that static methods can be referenced via this making it seem as if they are inherited.
It is bad practice to dispatch a static method via an instance of the class so it should always be A.staticMethod() which also clears up the inheritance misconception you have as B.staticMethod() would not refer to the same method as A if hidden/overriden.

Categories

Resources