I have a class that's essentially like:
class Child extends Parent {
public void reinitialize() {
super(); // illegal
}
}
Basically, I want to call the constructor again to reinitialize. I can't refactor out the initialization code into its own method, because Parent is a library class I can't modify the source of.
Is there a way to do this?
No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called at most once on any given object.
The usual answer is to refactor the code out into a normal instance method, but as you said, this is impossible.
The best you can do is to find a way to redesign to get around the need for reinitialization. Alternatively, if there's a specific behavior in the parent constructor you need, you might be able to duplicate it yourself.
The only work around for this is to either
create a new object each time you need to "re-intialise" it.
use delegation instead of inheritance, even if you have to use both. By using delegation you can replace the instance.
create a re-initialise method which does much the same thing as the parent constructor. e.g. replace fields or clear collections, using reflections if you have to.
One way to do this is provide a static method which returns a new Child object. Alternatively, you can simply create a new Child object in the client code. Either way, it sounds like you will be unable to reuse an existing object.
There are several ways to achieve this. One of them is create another method, for example "init". This "init" method should be invoked from either the constructor or the reinitialize method.
Related
I was looking through an old codebase and I found a method that only calls its parent:
#Override
public void select(Object item) {
super.select(item);
}
Would there be any use case for such a method? For me it looks like I could just remove it.
Removing it would make almost no difference. You will see a difference when using reflection and looking for the select method on the object. If you ask tell reflection not to look in the object's base class, it's not going to find the method after you delete it.
Yes, this method can be removed without changing the logic of your code.
Perhaps it used to have a different implementation which was removed, or was supposed to have a different implementation which was never written.
I'm doing this a bit backwards because I'm following a specific sequence of project instructions. I have two java classes. One of them simulates the grep function from Linux, and the other simulates the lineCount capability. I have them both implemented, but the NEXT step in the project is to create a superclass using the template method pattern that "will contain all fields and algorithms common to the other two programs".
There is a lot of common functionality between the two, and it is apparent what parts need to be part of the template and which need to be part of the implementations. For example, each of them needs to be able to create File objects based on the path string used to call the method, and search through the File's list method using a regex that is used to call the method. This is common functionality that should definitely be part of the template/abstract class.
It would be nice to be able to declare something like this:
public abstract class RegexCommands{
protected Variables;
public Map<things> myMethod(variables){
//common functionality which includes storing and using the variables
hookMethod(); //based on what you create in commonFunctionality
return resultAfterHookMethod;
}
}
public class Grep extends RegexCommands{
public hookMethod(){
class specific things;
}
}
public class lineCount extends RegexCommands{
public hookMethod(){
class specific things;
}
}
and just call it with
RegexCommands myObject = new Grep();
myObject.myMethod(variables);
and have it return what I'm looking for (grep command for the Grep object, lineCount for the LineCount object). However, the instructions specifically state that it will be called like so:
RegexCommands myObject = new Grep();
myObject.grep(variables);
RegexCommands myObject = new LineCount();
myObject.lineCount(variables);
and also that there are slight differences in the variables used. (lineCount doesn't need a substringSelectionPattern, for example) The way I have it set up now is that the hooked methods call super to their parent, and the template calls myMethod. This is obviously not the way that it is supposed to work. For one thing, it seems like I have had to introduce non-common methods to my template that just call the main template method, which means that one could, theoretically (although I haven't tested it), do something like
RegexCommands myObject = new LineCount();
myObject.grep(variables);
Which is not behavior that I want to allow and seems like it defeats the purpose of using the template. The other problem (that I have actually run into) is that my hookMethods don't seem to have access to the instance variables created in commonFunctionality (ie when I try to access a matcher that was created in commonFunctionality, it returns null even if I declare it as an instance variable instead of a method-level scope, like I would prefer).
So I'm kind of stuck and looking for some help. How do I have these objects use the myMethod pattern in the template without this terrible workaround that destroys the separateness of my objects, and how do I have the non-common methods use ArrayLists and/or Maps from the commonFunctionality without passing EVERYTHING over as parameters (which I have been advised not to do as it ruins the point of using templates)?
For one thing, it seems like I have had to introduce non-common methods to my template that just call the main template method,
Yes you would need to introduce such methods for your given requirement. But as you stated later that this would be incorrect as a LineCount object can call a grep method, this can be avoided by doing a instance of check in the non-common methods you would be writing. Doing the job if it fits the what is expected called or exiting otherwise.
For you original problem that you have run into
my hookMethods don't seem to have access to the instance variables created in commonFunctionality (ie when I try to access a matcher that was created in commonFunctionality, it returns null even if I declare it as an instance variable instead of a method-level scope, like I would prefer).
You can't define a abstract variable in java, the only legal modifier for variable in java are
public, protected, private, static, final, transient, volatile
you need to have a concrete implementation of commonFunctionality and you can have a getter method for it. You can define a abstract method for this in the abstract class. Refer to the answer of this post for more info Abstract variables in Java?
RegexCommands myObject = new Grep();
myObject.grep(variables);
RegexCommands myObject = new LineCount();
myObject.lineCount(variables);
This is only possible (in Java) if the interface/abstract class RegexCommands defines both methods. Thus both implementation needs to implement them, too. If you want to stick to that requirement you could do that and let Grep.lineCount() throw some exception.
A workaround could be to make RegexCommands to be a facade that only delegates method calls from RegexCommands.grep() to new Grep().myObject()
However, you should contact the requestor to clarify it.
I have a set of classes in my program which can be instantiated. Each class has a static method associated with it which updates a particular aspect of that class.
At run time the program chooses to use a number of the classes from the set.
Multiple versions of these classes are then instantiated as objects as the program runs.
Throughout the program there are key points where I need to call the static methods associated with the various classes but only the ones in use that the program picked at run time.
Is it possible for me to make a list/array containing the classes in use without instantiating them? So that I can then just go through that list and call the static method on each class?
The only other way I have found of doing it is instantiating one object for each class in use and storing them in an array and calling the methods from there. This seems a bit inefficient and not very elegant.
Any help is greatly appreciated.
You could use reflection to do something like this:
List <Class<?>> classes = new ArrayList<Class<?>>();
// alternatively, classes.add(com.foo.MyClass1.class);
classes.add(Class.forName("com.foo.MyClass1"));
classes.add(Class.forName("com.foo.MyClass2"));
// ...etc
Method m = classes.get(0).getDeclaredMethod("staticFunction");
m.invoke(null); // pass in an instance of the class if this is an instance method
Check out the javadoc for Class and Method.
I'm not sure why you want to avoid instantiation, but if the only thing you are doing is calling static methods, there is not reason to create objects. As for your question, you can create an Array of Classes without any problem. Remember that MyClass.class is actually an object of class Class, so this would work :
Class[] classes = new Class[] {MyClass1.class, MyClass2.class};
You can then use your logic to select some of them. When done, you can instantiate them using reflection :
classes[0].newInstance();
Hope it helps, if not, please precise your question. Note that the class objects themselves will be created (not sure you can prevent the class loader to load them).
You can have a list of Class objects such as
List<Class> myClasses = new ArrayList<Class>();
To add an item to the list you code something like myClasses.add(Class1.class);
That's one way to store a list of classes, without needing to create an instance of each one.
Util class in java can be made in two ways
class Utils
{
public static ReturnType someUtilMethod(
// ...
}
and execute util method by
Utils.someUtilMethod(...);
Or I can make
class Utils
{
public Utils(){}
public ReturnType someUtilMethod(
// ...
}
and execute util method by
new Utils().someUtilMethod(...)
What way is better? Are some differences between this ways?
Generally Util class contains Utility methods which doesn't need to store the state of Object to process and so static methods are good fit there
A utility function should always be static, unless for some reason it depends on the state of some other variables, and those variables need to be remembered between calls.
The latter should almost never happen, although something like a pseudo-random number generator might be a good case.
The Math functions are a good example of utility functions. When you call Math.sin() the result depends only on the supplied parameter. There is no "state" involved, so there's no need to create an object.
static access will be a better approach as in Util class hold methods which are not concerned with the attributes of the Objects.
Another example will be of Math Class.
Math class has no Instance variables.
And has private constructor, so no object can be created.
So in Math class case using static access like Math.PI is appropriate.
If you use a class that only has static methods, you will not need to instantiate the object everytime you need to use it, saving a line of code and some memory. Just remember to make the default constructor private, so that no one cane inadvertently instantiate it!
A utility class is just a place where to syntactically hold global functions in Java.
Your second example is not covered by the term "utility class". The definition of that concept includes non-instantiability of the class.
The reason to have instance methods would be dynamic method dispatch (to achieve polymorphism), or possibly hold some non-global state. But, as I said, then you would be out of the scope of the term "utility class".
What is the advantage of having constructor simillar to the one mentioned below:-
class A{
public A(A a){}
public A(){}
}
If you mean the one with the parameter, there's no reason for having that at all, given that it completely ignores the parameter, and there's already another constructor with the same effect.
If you can give a more realistic example, we may be able to give more useful information...
A(A a){/*do something*/} Can be helpful as copy constructor.
As others have said, you have a copy constructor. There are a number of reasons why you may want a copy constructor. Some of those are:
You can provide an alternative to the clone method. (Which is implemented via the Clonable interface.)
Copy constructors are easily implemented.
You can use another constructor to build the copy (by extracting data from the original object and forwarding to a regular constructor).
Check out the link I added to this post for more information about copy constructors and why you would want to use them (if you need them).
There is no advantage unless you need to have a copy constructor. I would suggest using the clone() method if this object should be clonable rather than using a copy constructor semantic.
You're question is very unclear, but basically if you hava a class, that has a constructor, that takes an instance of the same class, then you have a copy constructor. i.e. a constructor that creates a new instance with the same internal values as the original.
Edit -- assuming of course that your constructor does something other than just create a new instance.
It could also be useful in a number of delegation-based design patterns such as decorator or proxy etc.
Providing a default constructor might still be considered good practice, especially in scenarios where dependency injection or serialization are considered.