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.
Say I have an abstract class AbstractBarrelComponent that extends the Component class. The class uses a class named Barrel for some imaginary purpose.
Where should my Barrel class reside, if the only classes that would/can/should ever use it are the AbstractBarrelComponent and its subclasses?
By "reside" I mean should the class be in its own file, Barrel.java, or should it be a package-protected class in AbstractBarrelComponent.java? Is there a common convention for this kind of situation?
Different programmers and organisations use different standards for this and I don't think there is one right answer. The important thing is to pick a standard and stick to it.
My personal standard is that inner classes are always private. If a subclass needs access to it then it either should be in a outer protected class or access to its methods should be made available via delegation. The only downside to this is that you end up with more small classes. But, frankly, modern clean coding style relies on good IDEs that make it easy to navigate around your code so the need to group classes for navigation has mostly gone away.
As an aside, I feel it's unfortunate that the designers of Java did not make a distinction between protected for access by subclasses and protected for access by all classes in the same namespace. These are really quite separate use cases. In your situation there's a tendancy to make it an inner protected classes rather than an outer protected classes to restrict access to subclasses. It would have been better if there was a separate keyword for these two uses.
I just started learning to develop for the Android, and I come from a strictly C++ background. I found that Java does not support Multiple Inheritance, but do we really have to create a seperate .java file for every new Activity?
I have a TabActivity, with 3 more Activitys that make up the tabs. I want to create a List View on one of the tabs, but I am starting to get confused. Do I need to make another .java file that extends ListActivity? I can see even a relatively small application becoming extremely large if I am going to need to create a seperate .java file for every activity.
SIDE NOTE
If I want to add the ListView to one of my tabs, how would I do that? Nothing I have found thus far mentions how to add new activities to other Activities.
The other answers give good points about interfaces and that is probably more what you are looking for. However, for further information, no you don't have to create a new .java file for every new class, there are alternatives. However, keep in mind that more classes is not necessarily a bad thing. Your options are...
Nested Class:
public class A {
public/private class B {
}
}
Instances of B can access private variables of A but cannot be constructed without an instance of A (this is an approach often used for button handlers, etc.)
Nested Static Class:
public class A {
public/private static class B {
}
}
Instances of B cannot access private variables of A but they do not require an instance of A in order to be constructed. Instances of B can be instantiated anywhere if B is declared public, or only in A's methods if B is declared private.
Anonymous Class:
public class A {
private void setupLayout() {
...
button.addClickListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
handleClick();
}
});
}
}
This strange syntax creates a class that has no name and functions the same as a nested class (e.g. can access private variables). It's an alternative form of writing nested classes that is sometimes shorter but leads to very strange syntax.
Java doesn't support multiple inheritance on abstract or normal classes but on interfaces only.
What you can do is create abstract classes that extends a particular Activity and keep creating abstract classes until you have a class that inherit all your activity features.
Alternatively, is have a class that inherits multiple interfaces.
If you use an IDE to do this, the overhead of creating lots of file is much smaller.
However there are a few ways to have many classes in the same file. This includes a) using inner/nested classes b) anonymous classes c) enums d) package local classes.
The only thing you cannot do is easily if spread the definition of a class across multiple files.
Java does not support Multiple Inheritance
Workaround is you use interfaces
but do we really have to create a seperate .java file for every new Activity
No, if your activity can be done in an existing class or can be sub classed in an existing class. Java is built around creating classes for each activity.
Java doesn't allow multiple inheritance. But it does allow implementing multiple interfaces. You don't need to create a seperate file for each class (though it's a good practice). You can encapsulate sub-classes in the main class of your file.
ListView can be simply extended and you can use the corresponding extended class in the xml etc.
Java does kind of support multiple inheritance, if you just make the base classes abstract and call them interface instead of class.
You can simply declare a ListView in XML and call it in the Activity, no need to have a separate ListActivity, just for ListView. It's when your whole Activity is a ListView.
And as per the concerns about more classes, it's not a bad thing. More classes means more object oriented, not strictly though (Everything has a limit).
Multiple Inheritence was considered not good due to problem of diamond of death. So the work-around was to use Pure Virtual Classes known as Interface in Java (Interface means a normal class in Objective-C though).
I suggest you to read HeadFirst Java second edition, for better grip on terminology and their use. It's a good book for beginners.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Usage of inner class
When to user inner classes in java - I know one place event listener but except that where ?
What are pro- cons of using it ?
its same as When to use inner classes?
In general I would use inner classes when you need a one-off implementation of an interface or abstract class which doesn't need to be repeated. Event Listeners may be one good example of this.
At the moment I am working on a an application which uses Google Web Toolkit which relies heavily on inner classes as closures.
The pros of using inner classes are that you don't have to define a whole new class, you can just use them inline as and when you need them.
The cons are that:
You can't really re-use them in other places, i.e. an inner class may be better served by creating a more generic standard class and re-using it.
You can't define other methods inside an inner class and call them from outside the inner class.
From a design perspective when you to implement Composition in java you use inner classes.
In composition, the lifetime of the contained objects are managed by parent and the child type doesent make any sense outside the parent itself. For e.g. Entry(node) inner class in LinkedList.
In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like EventListeners or Runnables - is a best practice. They even were 'forbiden' in my first industry project.
Is this really a best practice? Why?
(I have to say that I'm using them a lot...)
-- EDIT ---
I can't pick a right answer in all these responses: there's part of rightness on mostly all of them: I'll still use inner classes, but I'll try to use them less often !
In my view, 90% of inner classes in Java code are either entities that are associated with a single class and were thus "shoved in" as inner classes, or anonymous inner classes that exist because Java does not support Lambdas.
I personally don't like seeing complex inner classes. They add complexity to the source file, they make it bigger, they're ugly to deal with in terms of debugging and profiling, etc. I like separating my project into many packages, in which case I can make most entities top-level classes that are restricted to the package.
That leaves me with necessary inner classes - such as action listeners, fake "functional" programming, etc. These are often anonymous and while I'm not a fan (would have preferred a Lambda in many cases), I live with them but don't like them.
I haven't done any C# in years, but I'm wondering if the prevalence of inner classes or whatever the C# equivalent is dropped when they introduced Lambdas.
Cleanliness. It's easier to comprehend code if it's broken into logical pieces, not all mushed into the same file.
That said, I do not consider the judicious use of inner classes to be inappropriate. Sometimes these inner classes only exist for one purpose, so I would then have no problem with their being in the only file in which they are used. However, this does not happen that much in my experience.
Anonymous classes are good to use when doing event based programming especially in swing.
Yes, forbidding inner classes is a useful practice, in that finding out a place forbids them is a good way to warn me off working there, hence preserving my future sanity. :)
As gicappa points out, anonymous inner classes are the closest Java has to closures, and are extremely appropriate for use in situations where passing behaviour into a method is suitable, if nothing else.
As some others said, many times, when you use an anonymous inner class, it is also used on some other places too...
Thus you may easily duplicate inner class code to many places...
This seems not a problem when you are using very simple inner classes to filter/sort collections, using predicates, comparator or anything like that...
But you must know that when you use 3 times an anonymous innerclass that does exactly the same thing (for exemple removing the "" of a Collection), you are actually creating 3 new classes on the java PermGen.
So if everyone use inner classes everywhere, this may lead to an application having a bigger permgen. According to the application this may be a problem... If you are working on the industry, you may program embedded applications that have a limited memory, that should be optimized...
Note this is also why the double curly brace syntax (anonymous innerclass with non-static initialization block) is sometimes considered as an antipattern:
new ArrayList<String>() {{
add("java");
add("jsp");
add("servlets");
}}
You should ask to people who forbids you to use them...
IMHO it all depends on the context...
Anonymous inner classes has benefits in being able to see the fields and variables around the "new" statement. This can make for some very clean design and is a quite nice (but a bit wordy) approach to "how can we make a simple version of lambda statements".
Named inner classes has the benefit of having a name, hopefully telling, which can be documented in the usual way, but which is tied together to the surrounding class. A very nice example is the Builder pattern, where the inner class is responsible for providing state for the initialization process instead of having numerous constructors. Such builders cannot be reused between classes, so it makes perfect sense to have the Builder tied closely to the parent class.
I suggest being cautious when using it if it needs a method parameter. I just found a memory leak related to that. It involves HttpServlet using GrizzlyContinuation.
In short here is the buggy code:
public void doGet(HttpServletRequest request, final HttpServletResponse response){
createSubscription(..., new SubscriptionListener(){
public void subscriptionCreated(final CallController controller) {
response.setStatus(200);
...
controller.resume();
}
public void subscriptionFailed(){
...
}
public void subscriptionTimeout(){
...
}});
}
So since the listener is kept by the subscription the HttpServletResponse is also kept in case the listener needs it (not obvious). Then the HttpServletResponse instance will be release only if the subscription is deleted. If you use an inner class that gets the response in it constructor it can be set to null once the call was resume releasing memory.
Use them but be careful!
Martin
One item that is not mentioned here is that a (non-static) inner class carries a reference to it's enclosing class. More importantly, the inner class has access to private members of it's enclosing class. It could, potentially, break encapsulation.
Don't use an inner-class if you have an option.
Code without inner classes is more maintainable and readable. When you access private data members of the outer class from inner class, JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In
general we should avoid using inner classes.
Use inner class only when an inner class is only relevant in the
context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the
context of an outer class.
Certain frameworks, like Wicket, really require anonymous inner classes.
Saying never is silly. Never say never! An example of good use might be a situation where you have some legacy code that was written by someone where many classes operate directly on a Collection field, and for whatever reason, you cannot change those other classes, but need to conditionally mirror operations to another Collection. The easiest thing to do is to add this behavior via an anonymous inner class.
bagOfStuff = new HashSet(){
#Override
public boolean add(Object o) {
boolean returnValue = super.add(o);
if(returnValue && o instanceof Job)
{
Job job = ((Job)o);
if(job.fooBar())
otherBagOfStuff.add(job);
}
return returnValue;
}
}
That said, they can definitely be used like a poor man's closures.
Inner classes are appropriate when trying to emulate multiple inheritance. It is similar to what happens under the hood with C++: when you have multiple inheritance in C++, the object layout in memory is actually a concatenation of several object instances; the compiler then works out how the "this" pointer shall be adjusted when a method is invoked. In Java, there is no multiple inheritance, but an inner class can be used to provide a "view" of a given instance under another type.
Most of the time, it is possible to stick to single inheritance, but occasionally multiple inheritance would be the right tool to use, and this is the time to use an inner class.
This means that inner classes are somehow more complex than usual classes, in the same way that multiple inheritance is more complex than single inheritance: many programmers have some trouble wrapping their mind around that concept. Hence the "best practice": avoid inner classes because it confuses your coworkers. In my view, this is not a good argument, and at my workplace we are quite happy to use inner classes when we deem it appropriate.
(A minor drawback of inner classes is that they add one extra level of indentation in the source code. This is a bit irksome at times, when one wants to keep the code within 79 columns.)
Anonymous inner classes are often used when we need to implement interface with one method, like Runnable, ActionListener and some other.
One more great appliance of anonymous inner classes is when you don't want to make a subclass of some class but you need to override one (or two) of its methods.
Named inner classes can be used when you want achieve tight coherence between two classes. They aren't so useful as anonymous inner classes and I can't be sure that it's a good practice to use them ever.
Java also has nested (or inner static) classes. They can be used when you want to provide some special access and standard public or default access levels aren't enough.
Inner classes are often used to "pass a behavior" as a parameter of a method. This capability is supported in an elegant way by other languages with closures.
Using inner classes produces some not elegant code (IMHO) because of a language limitation but it's useful and widely used to handle events and blocks in general with inner classes.
So I would say that inner classes are very useful.
yes it is good to use them, when you are trying to keep a class cohesive, and the classes should never be instantiated from outside their context of the outer class, make the constructors private and you have really nice cohesive encapsulation. Anyone that says you should NEVER use them doesn't know what they are talking about. For event handlers and other things that anonymous inner classes excel at they are way better than the alternative of cluttering up your package namespace with lots of event handlers that only apply to a specific class.
I tend to avoid non-static inner classes for the reasons given by other posters. However I have a particularly favourite pattern where a non-static inner class works very effectively: Lazy loading stateful classes.
A typical lazy loading stateful class is constructed with an entity ID and then on demand can lazily load additional entity information. Typically to lazily load the additional information we will require dependencies. But dependencies + state == anti pattern!
Non-static inner classes provide a way to avoid this anti-pattern. Hopefully the following simple example illustrates this better than words can:
/*
* Stateless outer class holding dependencies
*/
public class DataAssembler {
private final LoadingService loadingService;
#Inject
DataAssembler(LoadingService loadingService) {
this.loadingService = loadingService;
}
public LazyData assemble(long id) {
return new LazyData(id);
}
/*
* Stateful non-static inner class that has access to the outer
* class' dependencies in order to lazily load data.
*/
public class LazyData {
private final long id;
private LazyData(long id) {
this.id = id;
}
public long id() {
return id;
}
public String expensiveData() {
return loadingService.buildExpensiveDate(id);
}
}
}
Worth noting that there are many other patterns beyond the above example where inner classes are useful; inner classes are like any other Java feature - there are appropriate times where they can be used and inappropriate times!
When use or avoid inner class in Java?
The inner class has the following characters.
Anyway the .class file is separated as OuterClassName$InnerClassName.class
The class name and the class file name of the inner class always contain the outer class name.
The above characters disclose this fact. The outer class name is the mandatory information for the inner class.
We can derive this result from the fact. The inner class is good to be defined when the outer class is mandatory information of the inner class.
The characters of the inner class make developers sometimes annoying to debug. Because it forces the developer to know the outer class name with the inner class.
Suggestion
It can be a design principle to avoid defining the inner class except when the outer class name is the mandatory information of the inner class for the above two reasons.