How can I initialize interdependent final references? - java

I have a class and a factory function that creates new anonymous class objects extending that class. However, the anonymous class objects all have a method in which there are references to other objects. In my full program, I need this to create and combine parsers, but I've stripped down the code here.
class Base{
public Base run(){
return null;
}
static Base factory(final Base n){
return new Base(){
public Base run(){
return n;
}
};
}
}
public class CircularReferences{
public static void main(String args[]){
final Base a, b;
a = Base.factory(b);
b = Base.factory(a);
}
}
I get CircularReferences.java:17; error: variable b might not have been initialized. That's true, it wasn't, but can't I set aside space for these variables and then initialize them using references to these spaces, which will be filled with the proper values before they are ever actually used? Can I perhaps use new separately from the constructor? How can I create these variables so they reference each other?

The quick answer is that you can't do this. If you absolutely must do something like this, then use a private setter on the class and bind things together after they are constructed (i.e. use enforced immutability instead of final fields). Hopefully it's obvious that I don't think this is a good idea - I just wanted to provide a answer to your actual question before I answer the way that I really want to.
OK - now that is out of the way, here's the real response that is called for here:
Generally speaking, this sort of situation is a strong indicator that refactoring is needed to separate concerns. In other words, the Base class is probably trying to be responsible for too many things.
I realize that the example is contrived, but think about what functionality requires the circular dependency, then factor that functionality out into a separate class/object that then gets passed to both of the Base constructors.
In complex architectures, circular dependency chains can get pretty big, but strictly forcing final fields is great way to look for those types of refactoring opportunities.
If you have a concrete example, I'd be happy to help with some refactoring suggestions to break a dependency like this.
concrete example provided - here's my suggestion:
It seems like there is a concern of obtaining an appropriate ParseStrategy based on a token. A ParseStrategyProvider. So there would be a TopLevelParseStrategy that reads the next token, looks up the appropriate parse strategy, and executes it.
TopLevelParseStrategy would hold a final reference to the ParseStrategyProvider.
The ParseStrategyProvider would then need to have a registration method (i.e. registerStrategy(token, parseStrategy) ).
This isn't functionally much different from doing this with enforced immutability via a private setter (the registerStrategy method is for all intents and purposes the same as the private setter), but the design is much more extensible.
So you'd have:
public ParseStrategy createParser(){
ParseStrategyProvider provider = ParseStrategyProvider.create();
TopLevelParseStrategy topLevel = new TopLevelParseStrategy(provider);
provider.registerStrategy("(", topLevel);
// create and register all of your other parse strategies
return topLevel;
}

Related

Java: Using Static Methods for repeated code sections

So I'm learning Java (gasp bet you could've never guessed that), and today I'm focused heavily on making sure that I'm using static methods properly.
My big practice program right now is an account manager program, that I tweak and add to as I learn more and more concepts. One component of it is printing out a list of all the accounts added to the system. Because this list gets summoned more than once, I created a static method that can be invoked to generate it, and placed it above my main method in the code.
My question is: should I do this? Is it a good idea/good programming etiquette to create methods like this for repetitive sections of code? And if the answer to both of those is yes, should I make it a static method?
Here's the code for the static method I'm talking about:
/**
* accountList() method displays a list of all accounts currently loaded into the program
*/
public static void accountList(){
System.out.println(" ACCOUNT LIST");
System.out.println("NUMBER INFORMATION");
for(int num = 0; num < accountArray.size(); num++){
System.out.println(" " + (num + 1) + " " + accountArray.get(num).getAccountName()
+ " : " + moneyFormat.format(accountArray.get(num).getValue()) + " "
+ accountArray.get(num).getCurrencyType());
}
listMax = accountArray.size();
}
Then below this would be my main() method, and periodically within my main would be the invocation of this method to generate an account list:
public static void main(String[] args){
accountList(); //example of how I would invoke this method
}
So, do I have this figured out properly? Am I using this correctly? Thanks.
PS. My accountList() method is in the same class as my main() method, which is why there's no class name before it. That's also why I'm asking, because I know one of the main purposes of the term "static" is that it would be easily accessible from another class, so I'm not sure if it needs to be static if it's in this same class.
Is it a good idea/good programming etiquette to create methods like this for repetitive sections of code?
Having many small methods in stead of fewer large methods is a good practice in terms of maintainability and re-usability.
should I make it a static method?
Static methods are used when they do not depend on state of some particular instance of the class. It is in general avoided since subtype polymorphism is not available for static methods (they can't be overridden). Small utility methods are made static (like Math.sqrt or System.currentTimeMillis()).
Note: (Optional)
When you define methods to re-use the code, the most important aspect is the contract that the method is supposed to fulfill. So the methods should communicate with each other using arguments and return values for predictable behavior. Mutating state of class fields (or even worse static fields) is generally considered a bad idea (you have to do it though sometimes).
You could improve your method to something like following.
public static void printAllAccounts(List<Account> accountList) {
// Your code ...
}
This method specifies which accounts to print, and does not depend on state.
It would be even better if you can delegate it to another class and make it a non static behavior. That way if you come up with better way of printing all accounts, you can replace the behavior without touching this method.
Hope this helps.
Good luck.
Don't repeat yourself (DRY) is a widely accepted principle and good practice, and creating methods for code that would otherwise be duplicated is the simplest and most obvious form for this.
(In some languages/contexts people hint at the potential overhead of a method invocation and its impact on performance. In fact, inlining methods is a common optimization that compilers do. But modern compilers (and particularly, the Just-In-Time-Compiler of the Java Virtual Machine) do this automatically when it is appropriate)
Whether helper methods should be static has already been discussed elsewhere.
My rule of thumb here is: Whenever a method can be static, then it should be static.
A more differentiated view: When a method does not modify instance fields (that is, when it does does not operate on a mutable state), but instead only operates on its arguments and returns a result (and is a "function", in that sense), and when it should not be involved in any form of polymorphism (meaning that it should not be overloaded), then it should usually be made static. (One might have to take aspects of unit testing into account here, but that might lead too far now)
Concerning your specific example:
You have a different problem here: The accountArray obviously is a static field, as well as the listMax variable. And static (non-final, mutable) fields are usually a horrible idea. You should definitely review this, and try to make sure that you do not have static fields that describe a state.
If you did this, your method could still be static, and receive the accountArray as a parameter:
public static void accountList(List<Account> accountArray){
System.out.println(" ACCOUNT LIST");
...
}
However, in this form, it would violate another best practice, namely the Separation of Concerns. The method does two things:
it creates a string representation of the accounts
it prints this string to the console
You could then split this into two or three other methods. Depending on the indented usage, these could, for example, be
public static String createAccountInfoString(List<Account> accounts) {...}
public static void printAccountInfo(List<Account> accounts, PrintStream ps) {
ps.println(createAccountInfoString(accounts));
}
public static void printAccountInfo(List<Account> accounts) {
printAccountInfo(accounts, System.out);
}
(note that the method names indicate what the methods do. A method name like accountList doesn't tell you anything!).
However, as others have pointed out: Overusing static methods and passing around the information may be a sign of not properly using object-oriented concepts. You did not precisely describe what you are going to model there. But based on the keywords, you might want to consider encapsulating the account list in a class, like a class AccountList, that, among others, offers a method to print an account list to a PrintStream like System.out.
Here's what a static method is. A static method from the same class, you can just call without the class name, but a static method from another class, you would have to call with the class name. For example, if you have a static method called method1 in a class called Class1, and you're trying to call the method in a different class called Class2, you would have to call the method like this:
Class1.method1();
If you just use method1(), it would show up as an error, and it'll tell you that it can't find the method, because it only searches the class you're in for the method, and it doesn't find it. You would have to put the class name, Class1, so it knows to go search for the method in Class1, and not the class you're in.
As for whether you should use a static method or not, that depends, really, on your preference. Do you know the different between a static method, and a non-static one? I'll just gives you the basics for now. If you have more questions, you can ask.
Okay. A non-static method can only be called when you make an object out of the class the method is in. This is how you make an object:
(CLASS NAME)(OBJECT NAME) = new (CONSTRUCTOR NAME)();
The constructor's name is the same as the class name. And when you call the method, you would put (OBJECT NAME).METHOD NAME(); to call it. As for a static method, I already told you how you can call it. So. Anymore questions?
The use of static methods is something that could remember procedural programming. In fact, if you use static methods you cannot use OOP principles, like polymorphism.
First of all, it is not good that a method, which aims is to print a list, could change program state. Then, in the future, you may want to change the way the list is printed. Let say, you want to print it in file. How would you change your program to satisfy this new requirement if your ar using a static method?
Try to think more OO, and in the beginning, try to put your code inside a dedicated class (i.e. Printer). Then, you can extract an interface from that class, and finally try to apply some design patterns, like Strategy Pattern or Template Method Pattern.
static members of a class (that is variables, method) are not related/associated to the instance/object of the class. They can be accessed without creating object of the class.
General rule of using static method is - "Ask yourself is the property or method of a class should applicable for all of the instance of the class". If the answer is yes then you may use static member.
Consider the following example -
public class Student{
private int noOfStudent;
.......
}
Now you have a Student type. In this case you may consider to make the noOfStudent property static. Since this is not the property of a Student itself. Because all students of a class should share the same property of noOfStudent.
You can find more explanation here
Hope it will Help.
Thanks a lot.

When to use parameters and when to use instance data?

So I am writing a program right now and am conflicted about how I should program it. I have two options:
public class Translator {
private Translator(){}; //prevents instantation
/****
***Stuff
***/
public static String translate(String oldLanguage, String newLanguage, String text){
//METHOD Code
}
}
or
public class Translator {
private String oldLanguage;
private String newLanguage;
public Translator(String oldLanguage, String newLanguage){
this.oldLanguage = oldLanguage;
this.newLanguage = newLanguage;
};
/****
***Stuff
***/
public String translate(String text){
//METHOD Code
}
}
Which should I use and why? This will be the API end of my program.
Also, as programmer which do you find more convenient when dealing with APIs and why?
I would prefer to use the stateless version of translator, but I would prefer a state-full version of translated. The reason is, if you get rid of state then you can often get rid of an entire class of synchronization bugs while moving some of the important information closer to where it is actually used. Imagine, for example, if the two language variables were part of a 1000 line class. Would you want to look up how they are set every time they are used?
The reason I like state for translated is whereas a general translator can exist without knowing what languages it is going to be used for, if you lose what languages are used in a translated, you don't know as well what to do with it anymore (similar to losing your units in a math problem).
For the stateful option, a version I like better is, instead of:
...
private String oldLanguage;
private String newLanguage;
use:
...
private final String oldLanguage;
private final String newLanguage;
... and instead of something like:
myTranslator.setLanguages("spanish", "english")
Translated myTranslated = myTranslator.translate(original)
you can use:
Translator spanishEnglish = new Translator("spanish", "english")
Translated myTranslated = spanishEnglish.translate(original)
That's quite an interesting question, which doesn't have a single best answer. The criteria to choose, out of the top of my head, are mainly:
do you intend to instantiate a translator and reuse it several times with the same old and new languages?
does your translator need to keep some state in memory to be able to translate, without having to reload this state every time a translation is needed?
does your translator have other methods that also use the old and new languages?
is there somewhere in the application where the translator would have to be called without even caring/knowing about what the old and new language are, taking a pre-configured translator as argument?
do you need to be able to mock a translator and inject it in various other components of your code to unit-test them?
If the answers to these questions are yes, then a stateful translator (i.e. your second option) should be used. If the answers are no, then you could go with the first option.
As per the Object Oriented Programming standard, class is a representation of an entity. So you should define something as an attribute of class only if those are the properties of the entity represented by class. Having said that, add oldLanguage and newLanguage to your Translator class only if Translator entity has these attributes.
I would prefer to use the first one
public class Translator {
private Translator(){}; //prevents instantation
/****
***Stuff
***/
public static String translate(String oldLanguage, String newLanguage, String text){
//METHOD Code
}
}
why ?
the answer why should I instantiate an object to translate some thing if I can just do it directly .
Translator.translate(S,S,S);
A method of a class can (should?) be static when it does not access any non-static members or methods of this class.
Now this leads us to the question, when a member (field) of a class should be static or not:
A member (field) of a class must be non-static if it is relevant for defining the state of an instance (= object) of this very class.
So in summary, if something is relevant for the state of an object, then make it instance data, if not (only relevant for the calculation), then pass it as parameter into the method.
In addition to that, it becomes now clear, that it only makes sense to create an instance of a class, if you wish to represent a state. If zero non-static members exist, then you don't need to be able to create an instance of your class.

What is the point of "final class" in Java?

I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final class is simply a class that can't be extended.
(It does not mean that all references to objects of the class would act as if they were declared as final.)
When it's useful to declare a class as final is covered in the answers of this question:
Good reasons to prohibit inheritance in Java?
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
In Java, items with the final modifier cannot be changed!
This includes final classes, final variables, and final methods:
A final class cannot be extended by any other class
A final variable cannot be reassigned another value
A final method cannot be overridden
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x() and a is declared final, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
The best example is
public final class String
which is an immutable class and cannot be extended.
Of course, there is more than just making the class final to be immutable.
If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.
There's no violation of OO principles here, final is simply providing a nice symmetry.
In practice you want to use final if you want your objects to be immutable or if you're writing an API, to signal to the users of the API that the class is just not intended for extension.
Relevant reading: The Open-Closed Principle by Bob Martin.
Key quote:
Software Entities (Classes, Modules,
Functions, etc.) should be open for
Extension, but closed for
Modification.
The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.
The keyword final itself means something is final and is not supposed to be modified in any way. If a class if marked final then it can not be extended or sub-classed. But the question is why do we mark a class final? IMO there are various reasons:
Standardization: Some classes perform standard functions and they are not meant to be modified e.g. classes performing various functions related to string manipulations or mathematical functions etc.
Security reasons: Sometimes we write classes which perform various authentication and password related functions and we do not want them to be altered by anyone else.
I have heard that marking class final improves efficiency but frankly I could not find this argument to carry much weight.
If Java is object oriented, and you declare a class final, doesn't it
stop the idea of class having the characteristics of objects?
Perhaps yes, but sometimes that is the intended purpose. Sometimes we do that to achieve bigger benefits of security etc. by sacrificing the ability of this class to be extended. But a final class can still extend one class if it needs to.
On a side note we should prefer composition over inheritance and final keyword actually helps in enforcing this principle.
final class can avoid breaking the public API when you add new methods
Suppose that on version 1 of your Base class you do:
public class Base {}
and a client does:
class Derived extends Base {
public int method() { return 1; }
}
Then if in version 2 you want to add a method method to Base:
class Base {
public String method() { return null; }
}
it would break the client code.
If we had used final class Base instead, the client wouldn't have been able to inherit, and the method addition wouldn't break the API.
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be overridden by subclasses.
Preventing the class from being subclassed could be particularly useful if you write APIs or libraries and want to avoid being extended to alter base behaviour.
In java final keyword uses for below occasions.
Final Variables
Final Methods
Final Classes
In java final variables can't reassign, final classes can't extends and final methods can't override.
Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."
If the class is marked final, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A just won't work. It's basically a way to protect some parts of your code (to extent).
To clarify, marking class final doesn't mark its fields as final and as such doesn't protect the object properties but the actual class structure instead.
TO ADDRESS THE FINAL CLASS PROBLEM:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making it's constructor private.
One advantage of keeping a class as final :-
String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.
Developer of this class wanted no one to change functionality of this class, so he kept it as final.
The other answers have focused on what final class tells the compiler: do not allow another class to declare it extends this class, and why that is desirable.
But the compiler is not the only reader of the phrase final class. Every programmer who reads the source code also reads that. It can aid rapid program comprehension.
In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.
Yes, sometimes you may want this though, either for security or speed reasons. It's done also in C++. It may not be that applicable for programs, but moreso for frameworks.
http://www.glenmccl.com/perfj_025.htm
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
As above told, if you want no one can change the functionality of the method then you can declare it as final.
Example: Application server file path for download/upload, splitting string based on offset, such methods you can declare it Final so that these method functions will not be altered. And if you want such final methods in a separate class, then define that class as Final class. So Final class will have all final methods, where as Final method can be declared and defined in non-final class.
Let's say you have an Employee class that has a method greet. When the greet method is called it simply prints Hello everyone!. So that is the expected behavior of greet method
public class Employee {
void greet() {
System.out.println("Hello everyone!");
}
}
Now, let GrumpyEmployee subclass Employee and override greet method as shown below.
public class GrumpyEmployee extends Employee {
#Override
void greet() {
System.out.println("Get lost!");
}
}
Now in the below code have a look at the sayHello method. It takes Employee instance as a parameter and calls the greet method hoping that it would say Hello everyone! But what we get is Get lost!. This change in behavior is because of Employee grumpyEmployee = new GrumpyEmployee();
public class TestFinal {
static Employee grumpyEmployee = new GrumpyEmployee();
public static void main(String[] args) {
TestFinal testFinal = new TestFinal();
testFinal.sayHello(grumpyEmployee);
}
private void sayHello(Employee employee) {
employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
}
}
This situation can be avoided if the Employee class was made final. Just imagine the amount of chaos a cheeky programmer could cause if String Class was not declared as final.
Final class cannot be extended further. If we do not need to make a class inheritable in java,we can use this approach.
If we just need to make particular methods in a class not to be overridden, we just can put final keyword in front of them. There the class is still inheritable.
Final classes cannot be extended. So if you want a class to behave a certain way and don't someone to override the methods (with possibly less efficient and more malicious code), you can declare the whole class as final or specific methods which you don't want to be changed.
Since declaring a class does not prevent a class from being instantiated, it does not mean it will stop the class from having the characteristics of an object. It's just that you will have to stick to the methods just the way they are declared in the class.
Android Looper class is a good practical example of this.
http://developer.android.com/reference/android/os/Looper.html
The Looper class provides certain functionality which is NOT intended to be overridden by any other class. Hence, no sub-class here.
I know only one actual use case: generated classes
Among the use cases of generated classes, I know one: dependency inject e.g. https://github.com/google/dagger
Object Orientation is not about inheritance, it is about encapsulation. And inheritance breaks encapsulation.
Declaring a class final makes perfect sense in a lot of cases. Any object representing a “value” like a color or an amount of money could be final. They stand on their own.
If you are writing libraries, make your classes final unless you explicitly indent them to be derived. Otherwise, people may derive your classes and override methods, breaking your assumptions / invariants. This may have security implications as well.
Joshua Bloch in “Effective Java” recommends designing explicitly for inheritance or prohibiting it and he notes that designing for inheritance is not that easy.

Java abstract static Workaround

I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?
I want to have either an abstract class or an interface that mandates the inclusion of a static method in all of the classes that extend/implement this class/interface. Is there a way to do this in Java? If not, this may be my final straw with Java...
EDIT 1: The context of this problem is that I have a bunch of classes, call them Stick, Ball, and Toy for now, that have a bunch of entries in a database. I want to create a superclass/interface called Fetchable that requires a static method getFetchables() in each of the classes below it. The reason the methods in Stick, Ball, and Toy have to be static is because they will be talking to a database to retrieve all of the entries in the database for each class.
EDIT 2: To those who say you cannot do this in any language, that is not true. You can certainly do this in Ruby where class methods are inherited. This is not a case of someone not getting OO, this is a case of missing functionality in the Java language. You can try to argue that you should never need to inherit static (class) methods, but that is utterly wrong and I will ignore any answers that make such points.
You have a couple of options:
Use reflection to see if the method exists and then call it.
Create an annotation for the static method named something like #GetAllWidgetsMethod.
As others have said, try to not use a static method.
There are lots of answers about 'this does'nt make sense..' but indeed I met a similar problem just yesterday.
I wanted to use inheritance with my unit tests. I have an API and several its implementations. So I need only 1 set of unit tests for all implementations but with different setUp methods which are static.
Workaround: all tests are abstract classes, with some static fields with protected access modifier. In all implementations I added static methods which set these static fields. It works rather nice, and I avoided copy and paste.
I too am dealing with this problem. For those that insist that it "doesn't make sense", I would invite you to think outside of that semantic box for a moment. The program I am working with is inherently about reflection.
Reflection, as you know, can take three orders of magnitude longer than straight-up binary function calling. That is an inevitable problem, and the software needs to port to as many machines as possible, some of which will be 32 bit and slower than my development machine to begin with. Thus, the applicability of a class to the requested operation needs to be checked via a static method, and all of the reflective methods are run at once during module booting.
Everything works, first and foremost. I've built the entire thing. The only catch is that a module can be compiled in a .class without compile time checking to see if the identifying static function exists at all, resulting in an innately useless class. Without the identifier, and its included information, for security's sake the module is not loaded.
I clearly understand the issue with the complete definition of "abstract" and "static", and understand that they don't make sense together. However, the ability to have a class method that is compiler-enforced for inclusion is lacking in Java, and as much as I like the language, I miss it. Thus, this is a human constraint on every programmer that ever works on the software, which I'm sure we can all agree is a pain.
There's a lot of 'this makes no sense' or 'this can't be because' and 'why do you want it?' (or worse: 'you don't have to want it!') in all those answers. However, these answers also indirectly give reasons why it should be possible.
It must be differentiated between the concept and the implementation.
Sure, overriding a static method makes no sense. And it also isn't what the question was about.
It was asked for a way to force implementation of a certain static method (or constant or whatever) in every derived class of an abstract class. Why this is required it the matter of the one who wants to write an appllication with Jave, and no business of anyone else.
This has nothing to do with how the compiler compiles the method and how it is done at runtime.
Why shoudl it be possible? because there are things that are class specific (and not instance specific) and therefore should be static, while they NEED to be impleented in every single subclass (or class that implements an interface).
Let's say there is an abstract class 'Being'. Now there are subclasses like 'animals' and 'plants'.
Now there are only mammals and fishes allowed for animals. This information is specific to the animals class, not to any instance nor doe sit belong to any superclass or subclass. However, this information must be provided by teh class, not an instance, because it is required to properly construct an animal instance. So it MUST be there and it CANNOT be in the instance.
In fact, Java has such a thing- Every object has a class specific field 'class'. It is class-specific, not inherited, no override and it must be there. Well the compiler creates it implicitly, but obviously the compiler CAN do it. So why not allowing this for own fields too.
After all, it is just a matter of definition how the combination 'abstract static' is interpreted when the compiler checks the intheritance chain for abstract functions.
Nobody was ever demanding that there should be an inheritance of the superclass class functions (which could still make some sense, depending on what this function actually does - after all classes inherit static functions of their superclasses, even though you might get a warning that you should access it directly when you call it by the subclass))
But to summarize: the Java language offers no way to do it at compile time while there is no reason (othe rthan plain dogmatic) to not doing so.
The only way is to write a static final function to the abstract class that tries to find the static function/field of the subclass when it is loaded (or loads all existing subclasses and checks them). If properly made, it gives a runtime error on first use. Complex and dirty but better than nothing. At least it prevents bugs where you get the information from the wrong superclass.
It won't work for interfaces, though.
A type system allows you to express some constraints among types, but it's limited. That's why javadocs are littered with constraints in human language, asking people to follow rules that the compiler cannot check.
if you want to extend it beyond what language provides natively, you can write your own static analysis tool. that is not uncommon. for example: findbug. also IDEs do that too, they checking thing beyond what language dictates. you can write a plug in to enforce that a subclass must have a static method of such signature.
in your case, it's not worth it. have javadoc in the superclass urge implementors to include a static method, that's good enough.
I'll provide a convoluted way of expressing your constraint anyway, but DO NO DO IT. people get really carried away of make everything checkable at compile time, at the price of making code unreadable.
interface WidgetEnumerator
{
List getAllWidgets();
}
public class Abs<T extends WidgetEnumerator>
{
static List getAllWidgets(Class<? extends Abs> clazz){ ... }
}
public class Sub extends Abs<SubWidgetEnumerator>
{
}
public class SubWidgetEnumerator implements WidgetEnumerator
{
public List getAllWidgets() { ... }
}
How it works: for any subclass of Abs, it is forced to provide an implementation of WidgetEnumerator. subclass author cannot forget that. Now invocation Abs.getAllWidgets(Sub.class) contains sufficient information to resolve that implementation, i.e. SubWidgetEnumerator. It is done through reflection, but it is type safe, there are no string literals involved.
I think I can give you a better answer after seeing your edits--your best bet is probably a factory pattern. (Not lovely, but better than singleton).
abstract class Widget
public static Widget[] getAllWidgetsOfType(Class widgetType) {
if(widgetType instanceof ...)
}
class Ball extends Widget
class Stick extends Widget
class Toy extends Widget
This is not a very good way to do it, but it's typical. Hibernate is the tool you would normally use to solve this problem, this is exactly what it's designed for.
The big problem is that it requires editing the base class whenever you add a new class of a given type. This can't be gotten around without reflection. If you want to use reflection, then you can implement it this way (Psuedocode, I'm not going to look up the exact syntax for the reflection, but it's not much more complex than this):
public static Widget[] getAllWidgetsOfType(Class widgetType) {
Method staticMethod=widgetType.getStaticMethod("getAllInstances");
return staticMethod.invoke();
}
This would give the solution you were asking for (to be bothered by the need to modify the base class each time you add a child class is a good instinct).
You could also make it an instance method instead of a static. It's not necessary, but you could then prototype the method (abstract) in Widget.
Again, all this is unnecessary and sloppy compared to Hibernate...
Edit: If you passed in a live "Empty" instance of a ball, stick or toy instead of it's "Class" object, you could then just call an inherited method and not use reflection at all. This would also work but you have to expand the definition of a Widget to include an "Empty" instance used as a key.
Static methods are relevant to an entire class of object, not the individual instances. Allowing a static method to be overridden breaks this dictum.
The first thing I would consider is to access your database from a non-static context. This is actually the norm for Java apps.
If you absolutely must use a static method, then have it parameterised with instance specific arguments (of a generic type) to allow the different subclasses to interact with it. Then call that single static method from you polymorphic methods.
No. You can't do that. If you're willing to compromise and make the method non-static or provide an implementation of the static method in your abstract class, you'll be able to code this in Java.
Is there a way to do this in Java?
I don't think there is a way to do this in any language. There's no point to it, since static methods belong to a class and can't be called polymorphically. And enabling polymorphic calls is the only reason for interfaces and abstract classes to exist.
Create a context interface containing your method with a name that matches your problem domain. (Name it "World" if you absolutely have to, but most of the time there's a better name)
Pass around implementation instances of the context object.
Ok, maybe my question was poorly asked, it seems like most of you didn't get what I was trying to do. Nonetheless, I have a solution that is somewhat satisfactory.
In the abstract super class, I am going to have a static method getAllWidgets(Class type). In it I'll check the class you passed it and do the correct fetching based on that. Generally I like to avoid passing around classes and using switches on stuff like this, but I'll make an exception here.
static methods can't be abstract because they aren't virtual. Therefore anywhere that calls them has to have the concrete type with the implementation. If you want to enforce that all implementations of an interface have a certain static method, then that suggests a unit test is required.
abstract class A
{
public static void foo()
{
java.lang.System.out.println("A::foo");
}
public void bar()
{
java.lang.System.out.println("A::bar");
}
}
class B extends A
{
public static void foo()
{
java.lang.System.out.println("B::foo");
}
public void bar()
{
java.lang.System.out.println("B::bar");
}
}
public class Main
{
public static void main(String[] args)
{
B b = new B();
b.foo();
b.bar();
A a = b;
a.foo();
a.bar();
}
}
For what it is worth I know exactly what you are trying to do.
I found this article while searching for the reasons I can't do it either.
In my case I have HUNDREDS of classes that inherit from a central base base and I want simply to get a reference like this:
ValueImSearchingFor visf = StaticClass.someArbitraryValue()
I do NOT want to write/maintain someArbitraryValue() for each and every one of hundreds of the inherited classes -- I just want to write logic once and have it calc a Unique Class-Sepcific value for each and every future written class WITHOUT touching the base class.
Yes I completely get OO - I've been writing Java for about as long as it's been available.
These specific classes are more like "Definitions" as opposed to actual Objects and I don't want to instantiate one every time I just need to see what someArbitraryValue() actually is.
Think of it as a PUBLIC STATIC FINAL that allows you to run a Method ONCE to set it initially. (Kinda like you can do when you define an Enum actually...)
I'd make a WidgetCollection class with an abstract Widget inner class.
You can extend the WidgetCollection.Widget class for each of your types of Widget.
No static methods necessary.
Example (not compiled or tested):
class WidgetCollection<W extends Widget> {
Set<W> widgets = new HashSet<W>();
Set<W> getAll() {
return widgets;
}
abstract class Widget {
Widget() {
widgets.add(this);
}
abstract String getName();
}
public static void main(String[] args) {
WidgetCollection<AWidget> aWidgets = new WidgetCollection<AWidget>();
a.new AWidget();
Set<AWidget> widgets = aWidgets.getAll();
}
}
class AWidget extends Widget {
String getName() {
return "AWidget";
}
}
It doesn't make sense to do what you're asking:
Why can't static methods be abstract in Java

Testable Java Code: using model beans with a constructor

According to Misko Hevery that has a testability blog. Developers should avoid 'holder', 'context', and 'kitchen sink' objects (these take all sorts of other objects and are a grab bag of collaborators). Pass in the specific object you need as a parameter, instead of a holder of that object.
In the example blow, is this code smell? Should I pass only the parameters that are needed or a model/bean with the data that I need.
For example, would you do anything like this: Note. I probably could have passed the data as constructor args. Is this a code smell?
public Parser {
private final SourceCodeBean source;
public Parser(final SourceCodeBean s) {
this.source = s;
}
public void parse() {
// Only access the source field
this.source.getFilename();
...
... assume that the classes uses fields from this.source
...
}
}
public SourceCodeBean {
private String filename;
private String developer;
private String lines;
private String format;
...
...
<ONLY SETTERS AND GETTERS>
...
}
...
Or
public Parser {
public Parser(String filename, String developer, String lines ...) {
...
}
}
And building a test case
public void test() {
SourceCodeBean bean = new SourceCodeBean():
bean.setFilename();
new Parser().parse();
}
Another question: With writing testable code, do you tend to write TOO many classes. Is it wrong to have too many classes or one class with too many methods. The classes are useful and have a single purpose. But, I could see where they could be refactored into one larger class...but that class would have multiple purposes.
You will also notice that Misko Hevery advises to group parameters in classes, whenever the parameter count increases or in cases where this is logically acceptable.
So in your case, you can pass the SourceCodeBean without remorse.
A lot of what you are asking is highly subjective, and it is difficult to make useful suggestions without knowing the full scope of what you are trying to accomplish but here is my 2 cents.
I would go with your latter design. Create one class called SourceCodeParser, have the constructor take in filename, developer, etc, and have it have a parse method. That way the object is responsible for parsing itself.
Typically I prefer to pass in parameters to the constructor if they are not too numerous. Code Complete recommends a max of 7 parameters. If you find the number of constructor parameters to be cumbersome you can always create setters off of the fore-mentioned SourceCodeParser class.
If you want a way to institute different parsing behavior I would recommend using a Parser delegate inside of SourceCodeParser and have that be passed in as either a constructor parameter or a setter.
If you have a class who's sole purpose is to associate together various pieces of information, then I see no reason why that class should not be used directly as a parameter. The reason being that the class was coded to do exactly that, so why would you not let it do its job? So I would definitely prefer the former.
Now, this is assuming that the Parser actually needs the information as it's semantically presented in SourceCodeBean. If all the Parser actually needs is a filename, then it should just take the filename, and I would prefer the second method.
I think the only thing that might worry me here is SourceCodeBean becoming a kind of "kitchen sink" of information. For instance, the filename and format fields make perfect sense here. But do you really need the developer and lines? Could those be instead in some sort of associated metadata-information class?

Categories

Resources