I may be wrong as I have not got too much experience with Java, but here is a question.
I have a class which contains many methods (basically it is a simple library).
I create an object of this class let's say MyLibrary obj = new MyLibrary(parameters);
The parameters set up any necessary functionality for the library to run correctly.
Then I can call obj.getSomething/obj.setSomething/obj.createSomething etc etc...
In my main class I really need only one this kind of library object.
Now... Would it be more useful for me not to use it as an object, but put it as extends and then create a function inside of the library like a constructor which I would call manually?
EDIT:
The relation between the one class and MyLibrary is very close. Basically, I have many classes which do similar things but have some different higher layer functionality. So I separated method which must be in all those classes.
It seems it is very similar to shape class and triangle, circle, square example. So MyLibrary is similar to shape which contains all the foundation.
What you described strongly resembles a utility class, similar to Java's Collections. The class has only static methods, and a private constructor to prevent instantiations. This is a well-known idiomatic pattern in Java - you can use it to create your own groups of methods providing related functionality.
You should not extend, or even instantiate, utility classes at all. Starting with Java-5, you can statically import them so that you could use their methods without making an explicit reference to their class.
extends is used when you need an inheritance hierarchy. It seems more logical to put your code in two separate classes here, like you have it now.
Also, if your "library class" does multiple unrelated things, it should probably be split into multiple classes - one for each task.
You should really only use extends when you have a is-a relationship. So, you can think, is my main class a MyLibrary or should my class have a MyLibrary.
From your described problem, it sounds like having MyLibrary is the way to go.
With the limited detail that you have provided, you might want to consider the Singleton pattern.
extends should only be used when one object needs to inherit the characteristics and functionality of another one because they are very closely related. For example, if you have a Shape class, then you would extend Shape to create Circle, Square, and Triangle. Before you use extends you should learn more about inheritence and when you should and should not use it.
I would make this a static class to use. Similiar to javas MATH class API for math class. You can just use the methods of the class without making an object of it.
Well If your class if performing utility functions then you should mark all methods as static and use operations like
MyLibrary.doSomething();
MyLibrary.createSomething();
MyLibrary.getSomething();
But this wont allow you to keep some data members in the class and if you keep them they will be static as well.
I don't think so that extends suits your case.
Also if you want to keep only an object then you should look at Singleton A class for which only one instance can be created.
Assuming you are just using MyLibrary and may not alter it, you should use a wrapper that makes the whole thing a Singleton, as already proposed by Code-Guru.
public class MyLibraryWrapper {
private static MyLibrary instance = null;
private MyLibraryWrapper() {}
public static MyLibrary getInstance() {
if (instance == null)
instance = new MyLibrary();
return instance;
So in your code you would use
MyLibraryWrapper.getInstance().getSomething();
Best way to create singleton in java 1.5 or above is to use ENUM.
public enum Test {
INSTANCE;
}
INSTANCE is the only instance of Test class.
Related
I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.
This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 7 years ago.
I have seen several threads that define extending a class as a way for a personalized class to inherit the methods of the class that it is extended to. When you import a class and create an instance of that class you have access to its methods, can someone please explain to me how extending a class to provide those methods to your own class is effectively different, in other words, the only difference I see is that when you import you create an instance of a standardized class, and when you extend you effectively turn your personalized class into the standardized class only with a different name. I am aware I am wrong, but the answers I have read have failed to help me fundamentally understand the difference.
Importing and extending are two very different things.
Importing
Classes are organized in packages, which provide a namespace facility that avoids name conflicts. Importing allows you to use the class in your code without the namespace information.
Importing is optional. You never have to import anything if you always use the fully qualified name of the class, but that makes your code hard to read.
If you want to make a list of Calendar objects, for example, you either import java.util.List, java.util.ArrayList and java.util.Calendar and use:
List<Calendar> array = new ArrayList<>();
Or import nothing and use:
java.util.List<java.util.Calendar> array = new java.util.ArrayList<>();
Sometimes you have two classes with the same name in different packages. In that case, if you use both of them in your code you can't import both. You will have to refer to one of them by their fully qualified name. For example:
List<java.awt.List> array; // you have to import java.util.List, but can't also import java.awt.List
Extending
When you extend in Java you are saying that the subclass is a type of the original class. That's the most important aspect you have to be aware of when using extends. Is you say Bus extends Vehicle you are saying that Bus is a Vehicle. You not only inherit all the non-private methods and fields of the superclass, but also can use the subclass anywhere you could legally use the superclass. For example, if you have this method:
public park(Vehicle v) {
v.drive();
v.turn(Direction.LEFT);
v.stop();
}
you could pass a Bus as an argument, because Bus is a Vehicle.
parkingLot.park(new Bus());
and the drive(), turn() and stop() methods will be called in the Bus. That is polymorphism.
Although you inherit methods, inheritance is not the best way to reuse code. Most of the time when you need to reuse code you can do it by using composition (making your class have a reference to another class, instead of being one). A Car shouldn't extend Motor because a car is not a motor, but it could have a motor and delegate a call to the motor's turnOn() method when the car's drive() method is called.
You can also have polymorphism without inheritance in Java using interfaces.
To make a simple example (but bad :/ ). Lets say you have a Person class.
public Person
{
int age;
string name;
}
Then you have different type of persons that inherit the Person class, eg.
public SoftwareDeveloper extends Person
{
string codingLanguage;
}
Now you can easily create a SoftwareDeveloper and use its attributes like this:
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.name);
}
If you would "import" instead, you would have to create an instance of Person in SoftwareDevelopers constructor and make it public. So your code would be to access the attribute:
public SoftwareDeveloper
{
public Person person;
string codingLanguage;
public SoftwareDeveloper(){
person = new Person();
}
}
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.person.name);
}
I think in small scale your reasoning works fine but the idea of extending is that your class inherits all the methods of the extended class.
But if you start with a simple idea or program and want to expand it massively the use of instantiating all the classes you need becomes much more consuming. On even a simple idea the increase in imports can explode.
Example:
Animal - warm blooded - biped - human
Animal - warm blooded - quadruped - feline - cougar - panther
Now you want to have your panther have all the methods of the 5 classes its built apoun.
So that 5 imports and objects you have to manipulate to get to all the methods you want to access. But if all these are extending each other you just have direct access to the methods. And this is a simple example now imagine a huge accounting program.
So point I trying to make....I think...Is that its much more prevalent and easier to understand the usefulness in extending classes when you look at it in the large scale.
Hope this helps or makes as much sense as it does to me.
Extending a class means that your class is "inheriting" the methods of the standard class; in other words, you are taking an existing class and building your class on top of it. That is how Java manages all objects (i.e. every class that you create actually extends the default Object class). When you import a class, on the other hand, you have access to all its functionality, but you cannot build on top of it as you could with inheritance.
Let's start with importing a class. You import a class in order to use it in another class, if that class is in another package. It's really just a shortcut that's saying when you see a class called X used, what I really mean if com.somepackage.X.
Extending is taking a class and using it as a base for a new class. There's alsorts of reasons to do this (well beyond the scope of an answer here) but the important thing is that you inherit the behaviour of the class you are extending and have the choice of whether or not to override that behaviour or add additional behaviour.
For good example of classes being extended, look at the Collection API in java.util where you can see java.util.AbstractList is extended to ultimately create two different types of list, each with different characteristics - java.util.ArrayList and java.util.LinkedList.
Lets look on an example.
We have class which provide an update function to database and containing a String variable.
public class DBupdate {
public String StrVar = "Hello";
...
public void doUpdate(String expression) {
try {
connect();
runExp(expression);
disconnect();
} catch ...
}
}
If you import it. You will do something like
log(new DBupdate.StrVar);
String myExp = "UPDATE ..."; // SQL
new DBupdate.doUpdate(myExp);
If you extend.
log(StrVar);
String myExp = "UPDATE ..."; // SQL
doUpdate(myExp);
doUpdate() function and StrVar became part of your new class. So all functions and variables (which are public or protected) are part of your new class (inherited).
Example for usefull import (and not extend/inherit) is log4j. It is doing work like writing to console and into a file. But you want just to use it "log" function and no speacial functions it is using for its work.
Example for usefull inherit is java.lang.Thread. If you class became a thread it can be treated as a Thread and will be splitted to run parallel, if you use java.lang.Thread function "start()". (Override run() method to do so some stuff...)
At the very simplest case it can be said that, Import Statement improves readability and reduces the length of the code.
In java we implement dynamic loading, language import statement no class file is loaded at the time of import statement, when ever we are suing a class, at the time of only the corresponding .calss file will be loaded.
Extends-
In Java, when we wish to extend the usefulness of a class, we can create a new class that inherits the attributes and methods of another. We don't need a copy of the original source code (as is the case with many other languages) to extend the usefulness of a library. We simply need a compiled '.class' file, from which we can create a new enhancement. I could not find a better way to explain so just refer this link..(source -http://www.javacoffeebreak.com/java104/java104.html)
My application has the following class:
MyTextField, which extends JTextField.
I, however, need the methods inside MyTextField in the following class:
MyPasswordField, which extends JPasswordField.
Multiple inheritance isn't allowed in Java, and I'd like to avoid to copy-paste 85% of the class because of this. How to overcome this "limitation"?
Use a helper class that defines the shared functionality. Declare a field in each of MyTextField and in MyPasswordField to hold an instance of the helper class. Relay calls to the helper as needed for the shared functionality, which then only needs to be coded once.
Why don't you use Composition instead of Inheritance.
Your MyPasswordField class can contain an instance variable to myTextField, then you can just use the method using your instance and it's methods.
Let me know if I am going on the wrong track and you expect something different.
You can achieve this with the help of a Helper class with static methods, so you don't need keep an instance of the helper class in your testfields classes.
I am trying to refactor a project in which there are same methods which are spread across various classes. To reduce code duplication, should I move the common code to an abstract superclass or should I put it in a static method in a utility class?
EDIT
Some of the methods are for generic stuff which I believe can be made static. While there are others which refer to attributes of the class, in which case I think it makes more sense to make it as an abstract super class.
Well, I follow a rule: Don't use base class to remove code duplication, use utility class.
For inheritance, ask question to yourself: Does Is-A relationship exist?
Another rule, which most of the times is correct, is: Prefer composition over inheritance
using static utility class is NOT true composition but it can be called a derivation of it.
Apply these rules to your secenrios and take a decision keeping in mind maintanence and scalability. However it will be good if you could add more details to your quesiton.
It depends on what your code is doing. Are they utility methods? Are they specific/specialized class methods? Is this a heavy multithreaded application?
Keep in mind that if you make them static and your application is multithreaded, you will have to protect them w locks. This, in turn, reduces concurrency. In this case, depending on how many threads call that same piece of code, you might consider moving it (the code) to a super class.
Another point to consider may be the type of work these functions do. If that is scattered, you should create a facade / helper / util class with static methods.
As others have mentioned the answer to this depends on the context of the problem and the duplicated code.
Some things to consider
Does the duplicated code mutate the instance of the object. In this case a protected method in a common abstract class
Instead of Static utility class consider a singleton, Static methods can be problematic for pure unit testing although testing frameworks are getting better at this.
Inheritance can be tricky to get right, think about if these objects from the different classes are really related and require some OO re-factoring ? or are they disjoint pieces of domain logic that happen to require similar bits of code.
If it does not use any class members you might do it static!
But you should do it in a abstract class or mother class
If the methods use many fields or methods of the class they should not be static.
If they are something that a subclass might want to modify they should not be static.
If the methods should be part of an Interface they cannot be static.
Otherwise it's your call and you will probably change your mind later. :-)
At first glance, I would say that it would be better to make the common code as a public static method in a public class. This will make the method useful to any class just by using
UtilityClassName.methodName();
This is better then making it a concrete method in an abstract super-class because then you will always need to extend this super-class in all the classes where you want to use this one single method.
But now, as you said that the method's behavior depends on some variables. Now, if it depends on the instance variables of different classes, then better add this method in an interface and let all your classes implement this interface and have their own implementation of the same.
But again if these variables are constant values, then have these constant values in an interface. Implement these interface in your utility class. And again make it a static method in that utility class which will directly use these constants.
For e.g. Consider foll. common code of returning area of a circle.
public interface TwoDimensional{
double PI = 3.14;
}
public class MyUtility implements TwoDimensional{
public static double getCircleArea(double radius){
return PI*radius*radius;
}
}
Here, you can see that method getCircleArea() depends on the radius which will be different for different classes but still I can pass this value to the static method of myUtility class.
I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.