Using multiple classes without creating objects of each - java

I am new to java and stackoverflow
I have
class Assemble()
class Start()
class Ignite()
class Move()
...... There are still 12 classes
I want use methods inside these classes
but
i should not create objects of them
i cannot use extends for all these also
i there any way possible?
Please bare anything silly, i am not able to figure out.
And this is my first question hear.
the finaly class is
class run
{
public void run_simple()
{
// hear i should be able to access all methods of above class
}
}

If you use an object oriented language (as java) the way it is meant, your whole program is about creating and using objects (as mentioned in many comments). There are some valid technical reasons not to create objects and to use static methods ("it's tedious" is not one of them). There are environments that forbid to use inheritance.
Please state these reasons, otherwise we have to assume that you don't understand some basic concepts of object oriented languages and that your "restrictions" must be ignored.
Most "restrictions" of object oriented programming are intended to help you structure your solution/program. If you see them as real restrictions, the structure of your program might very well be bad.
I'd like to give an example on how something like this might look "the OO way". This might not fully match your project, but should show you that creating objects must not be an issue programmer effort wise.
First we need an interface that defines what one of your actions (thats what I call your classes) looks like
interface Action {
public void run();
}
The following classes define the concrete actions. Their constructors might take parameters configuring details on how to execute them. In the run()-method of each class, you program on what an action does when executed.
class Assemble implements Action {
public void run() {...}
}
class Start implements Action {...}
class Ignite implements Action {...}
class Move implements Action {...}
The controller does the "run everything". That's basically your "overhead" for creating objects!
class Controller {
/** Returns a list of the configured action objects. */
public static List<Action> buildActions() {
List<Action> actions = new LinkedList<Action>();
actions.add(new Assemble(parameter)); // or whathever parameters you need
actions.add(new Start(parameter1, parameter2));
actions.add(new Ignite());
actions.add(new Move());
}
/** Build the list of actions and run one after the other. */
public static void main(String[] args) {
List<Action> actions = buildActions();
for (Action action: actions) {
action.run();
// here you could add logging, profiling etc. per Action.
}
}
}

Related

Clarification needed on Concept of a listener anonymous class in java

I'm new to java. What is the purpose of a listener anonymous inner class design? I heard that anonymous classes are used as listeners in java. And that no one really creates inner classes or even static inner classes. I'm not sure what that means. could some one explain these concepts a bit? Especially this listener design and how its created via an anonymous class.
Thank you in advance.
An anonymous listener would usually look something like this:
myControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle event
}
});
Using an inner class to accomplish the same goal would usually look something like this:
public void init()
{
myControl.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Handle event
}
}
Now consider what the two would look like in the scope of a much larger program. The anonymous listener is still right there at the spot where you're adding it. The inner class may be somewhere else in the source file entirely. With a good IDE, that difference can be minimized (such as a members browser), but is there really a need for an entirely new class for something you're going to use once?
Of course, depending on the exact needs of your application, a separate class might in fact be a better choice. If, for example, you have many listeners that differ only a little bit, you could construct something along these lines:
public void init()
{
myControl1.addActionListener(new MyActionListener("foo"));
myControl2.addActionListener(new MyActionListener("bar"));
myControl3.addActionListener(new MyActionListener("baz"));
}
private class MyActionListener implements ActionListener
{
private String word;
public MyActionListener(String word)
{
this.word = word;
}
public void actionPerformed(ActionEvent e)
{
// Handle event
System.out.println(word);
}
}
As far as static classes go: in Java, an inner class can be marked static, and all this does is prevent it from having a reference to the instance of the enclosing class. (For example, MyProgram.MyStaticClass would not be able to access any members of MyProgram which weren't static, unless it creates a new instance of MyProgram.) This may help with separation-of-concerns, but doesn't change very much when it comes to listeners.
That's not true, that no one creates named classes to handle events. Yet most of the time event handlers actually are anonymous classes. The reason for that is that anonymous classes offer less code and less files to maintain and it's easier to read a code when you don't have to jump between many small files. Anonymous classes shouldn't be too long (i.e. no more than ~20 lines of code), if they are longer, they should be converted to named classes. Anonymous classes are common in java version less than 8. In java 8 there are Lambda expressions, which are similar to anonymous classes, but they are more compact.
In languages with support for first class functions listeners can be implemented like this:
def myFunction() { //code }
button.onClick(myFunction)
for simplicity some languages has the capability to define anonymous functions (aka lambdas):
button.onClick({ // code})
Are called "anonymous" because don't need a name to reference it, are used in place.
Java don't has first class functions, instead the listener pattern is implemented with a class that implement some interface:
class myListener implements ButtonListener {
public void listen(...);
}
button.onClick(myListener)
Analogous to the anonymous functions, for simplicity, java has the concept of anonymous classes, you can do:
button.onClick(new ButtonListener {
public void listen(..) { //code }
});
Note: this are simple "ilustrative" examples with an invented on the fly api :P
In java 8 first class functions (closures) are introduced, a huge and very good addition to java IMMO.
Inner classes: sometimes is good that one class is defined within the scope of another class, not the most useful java property IMMO, i use occasionally but can live without it in other languages.

When to use Single method Interfaces in Java

I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.
And the implementer class will implement many interfaces with single methods.
In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example ResultSet? Or is there some design standard which advocates the use of these type of interfaces?
With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.
So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.
Example:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
#Override void foo(int i){ Y.bar2(i); }
});
}
Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".
Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)
Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.
In what scenarios does it make sense to keep single method interfaces?
In such a scenarios when you need an interface with only one method.
Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.
Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:
public interface Quackable {
public void quack();
}
public class Quacks implements Quackable {
public void quack(){
//quack behavior
}
}
public class DontQuack implements Quackable {
public void quack(){
//dont quack
}
}
public class QuackableDuck{
Quackable quack; //add behavior dynamicall
}
So QuackableDuck class can add feature dynamically.
quack = new Quacks();
//or
quack = new DontQuack();
So similarly you can add multiple behavior to the class dynamically.
You create interfaces not according to the number of methods in it but to define behaviour expected by components of your systems to deliver a single responsibility to their neighbors. If you follow this simple principle/rule, you might or might not end up with single method interfaces, depending on the responsibility you are defining. I like to keep tests stupid simple and the application very flexible so I usually have many of those

How to implement code to multiple classes in Java?

I have two classes: JDialog and JFrame (see below). Now I want them to get some extra functionality, but I want the two classes both to extend my code, without writing the code twice. Is there a way to do that?
java.awt.Window » java.awt.Dialog » javax.swing.JDialog
java.awt.Window » java.awt.Frame » javax.swing.JFrame
(PS: Actually, I want to "rewrite" the source code of java.awt.Window, adding extra functionality. I know that's not possible, but that would be a "solution", because if I do so, both JDialog and JFrame would extend my brand new methods.)
Example:
Suppose I want to add the method moveWindowToMagicPositionOnScreen(), moving the window to a user-friendly position on the screen—I know, it's just an example. I want the method to apply to both JDialog and JFrame. Using inheritance, I must write two classes, for example MagicJDialog and MagicJFrame, each implementing the method moveWindowToMagicPositionOnScreen() in exactly the same manner. Well, that's pretty redundant. So I don't want to have the code written twice. In some way, I want one class to use the code of the other class.
The interface / delegate / composition ideas are probably the "cleanest". But an acceptable and arguably simpler alternative is to make a utility class with a static method.
public static moveWindowToMagicPositionOnScreen(Window window) {
// calculate new x and y
window.setLocation(x, y); // or perhaps setBounds()...
}
In practice, I'd probably put the calculation logic into another method, computeMagicPositionOnScreen(). If it makes sense (it may not) this static utility class could actually be a "real" (non-static) class, say MagicPositionCalculator, that might have multiple instances, say one per each screen, one for really large screens, one for power-users, etc...
Unfortunately, Java does not support mixins. The easiest and clearest approach to take here would be to use composition, in which case you only have to write the wrappers twice, but the actual implementation lives in a single location.
Like several others have suggested, prefer composition over inheritance. However, you can create an common interface for your method:
public interface Magic {
void moveWindowToMagicPositionOnScreen();
}
If the code that moves the window is exactly the same create a delegate class:
public class MagicDelegate implements Magic {
public void moveWindowToMagicPositionOnScreen() {
// TODO implement logic
};
}
Then have your two classes implement the Magic interface using MagicDelegate:
public MagicJDialog implements Magic {
private MagicDelegate magicDelegate; // TODO instantiate
public void moveWindowToMagicPositionOnScreen() {
magicDelegate.moveWindowToMagicPositionOnScreen();
}
}
and
public MagicJFrame implements Magic {
private MagicDelegate magicDelegate; // TODO instantiate
public void moveWindowToMagicPositionOnScreen() {
magicDelegate.moveWindowToMagicPositionOnScreen();
}
}
Side note, the code that moves the window is only partially the same, you can either choose to ignore the MagicDelegate class or create a template class with the common parts:
public abstract MagicTemplate implements Magic {
public moveWindowToMagicPositionOnScreen() {
// common logic
implementationSpecificLogic();
// more common logic
}
protected abstract void implementationSpecificMethod();
}
Now, the MagicJDialog class and the MagicJFrame class can extend the MagicTemplate class and implement the implementationSpecificLogic() method.
Try this,
I think you want to apply DRY (Don't Repeat Yourself) design principle and partially LSP (Liskov substitution Principle), if you want some method to be stored in a class, and then use this method from other two classes, then I think prefering composing over inheritance will be a good idea. Cause you will be able to use the desired method without inheriting the methods that you don't want.

Java OO Design help - how to abstract out a save method?

I have a Preference class (module) that's used across several different apps. Basically it's a cache of the preferences so that the systems don't have to call the backend all the time. It's similar to a cache but with some additional niceties such as isPreferenceSelected, has some helper methods, etc.
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care. The issue is that it's not an abstract class so I can't override the static methods and even if it was, I don't want to create a million instances because I don't want to load the preferences each time. And I can't create a abstract singleton either.
Therefore I'm not sure what to do. Here is a code snippet of what I'd like to do with comments:
// Please ignore the missing Generics, etc.
public class Preference
{
private static HashMap preferences = new HashMap();
public static ...
// Some preferences are objects, such as images, etc.
public static setPreference(String name, Object value)
{
.. some helper code
preferences.put(name, value); // ignoring issues with if it already exists ;)
savePreference(name, value); // saves to database, flatfile, etc.
}
}
That was the core class/code that the different systems leverage. Now what I'd like to do is say in a webapp, a desktop app, etc., be able to use this class in my code such as:
public someFunction(...)
{
.. do some cool code
Preference.savePreference("logoImage", image);
}
And have the savePreference() method not just save the in-memory preferences, but also save it to the external source. Otherwise everywhere I have savePreference() I have to follow it by a db call savePreferenceToDB(), a FlatFile call such as savePreferenceToFlatFile(), and so on. This is very error prone, someone somewhere will forget to save it. Plus it really makes no sense to sprinkle the save to permanent storage code everywhere with this type of code when it should really only be done once. Also remember that the main module has no idea if the permanent storage is a database, an xml file, a flat file, etc.
Hint: If I did Preference.getInstance().savePreference() that wouldn't work because you can't abstract a singleton. And I can't create a static method savePreference() because it's not possible to override a static method.
The only options I can see is to create some kind of complex Factory pattern, but that seems like a lot of overkill to me. Therefore any suggestions would be greatly appreciated.
This sounds like something that your dependency injection (DI) container should be handling, not a complex factory pattern.
That is, I think you should ditch the usages of static, have whatever creates the other applications inject an instance of Preference into your applications. You can do this without a DI framework if you just take the Preference as a parameter in your constructor for whatever other classes depend on it.
Edit: Let me give you an example of dependency injection without a framework. Take the following set of classes:
public class Preference
{
private String userName;
public Preference(String userName)
{
this.userName = userName;
}
public void savePreference()
{
// Default implementation saves it to the screen. ;-)
System.out.println(userName);
}
}
public class Foo
{
private Preference p;
public Foo(Preference p)
{
this.p = p;
}
}
public class Bar
{
private Preference p;
public Bar(Preference p)
{
this.p = p;
}
}
public class Main
{
public static void main(String[] args)
{
Preference p = new Preference("Mike");
Foo f = new Foo(p);
Bar b = new Bar(p);
}
}
This is a simplistic example, but it satisfies your requirements:
The Preference instance is only created once
The Preference class can be extended by whoever implements the Main class to instantiate whatever kind of Preference subclass they want to, if they wanted to persist it in a relational database (or whatever)
By avoiding having static calls in the first place you also make it possible for your someFunction() example to be unit tested without pulling in a potentially big, complicated preferences framework. Rather, someone implements a mock Preference subclass and passes it into the class that runs someFunction(). Your code will be much more testable that way.
#Mike says:
... I think you should ditch the usages of static
#Stephane responds:
... what is the major issue with static methods?
It is not just static methods. It is also the singleton instance.
Basically, they are inflexible:
They make it difficult to do things in alternative ways, as illustrated by your problem. If you didn't use a static method and a private singleton instance, you could create a Preferences interface and/or abstract base class, together with implementations that load and save the in-memory preferences in different ways.
Static instances tend to make testing harder. For instance, if you had a preferences UI that made use of your Preferences class, you couldn't unit test the UI classes using a "mock" version of Preferences. (Or at least, it would be a lot harder to do.)
Statics tend to make it difficult to reuse your code because of the hard dependencies on specific named classes and specific implementations.
Statics are non-OO. This is not intrinsically a bad thing, but it does mean that you can't make use of the nice properties of OO ... like overriding and polymorphism ... when you use statics.
If you have a significant number of these static methods / static objects in your application, a DI framework is a good solution. But as #Mike says, using Factory methods and passing objects in constructors will work just as well in many cases.
You commented:
One of the reasons I have it as a static class is because the preferences are loaded at startup. After that they stay in memory in the one static object. With DI, each time I create the object, I'd have to reload the information into memory from the data source. This defeats the whole purposes of having a Preferences Object (that pretty much acts like a cache with benefits).
This does not require you to use a static instance.
With DI (or explicitly wiring instances via constructors), you don't create the Preferences object more than once. You create it once, and then inject it as many times as required.
There is a halfway between your current approach with a static method that wraps a static instance of a hard-wired class and full DI. That is a what can best be described as a static holder; e.g.
public interface Preferences {
// Preferences API
}
public abstract class PreferencesBase implements Preferences {
// Implement as much if the API as makes sense
}
public class FileBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class DatabaseBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class ApplicationPreferences {
private static Preferences instance;
private ApplicationPreferences() { }
public Preferences getInstance() { return instance; }
// Call this once during application startup with the
// Preferences instance to be used by the application.
public void initPreferences(Preferences instance) {
if (this.instance != null) {
throw new IllegalStateException(...);
}
this.instance = instance;
}
}
I think it might take some rework of your design (unfortunately, I don't have a decent whiteboard in my apartment yet, so I can't easily sketch things out to conform), but I immediately thought Strategy pattern as soon as you said this:
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care.
You might have an abstract Preferences class that has every method but saving (and loading) implemented. In the sense of the pattern, this would be the Strategy interface. Your different types of saving and loading would be handled by the concrete implementations.
Create an interface for your preference manipulation class:
public interface PreferenceHandler {
void savePreference();
void readPreference();
}
Pass an instance of type PreferenceHandler to your class with all the static methods.
Invoke the methods on that class within your class.
Though, not lovin' all those static methods. It's probably why you're having so many issues here. Create a factory that gives you a copy of the class if you don't want to be creating lots of copies of it. But static methods really impede code re-use and extension. Or perhaps use a framework like Spring to manage classes of this sort.

Example of inner classes used as an alternative to interfaces

What I was told, which sparked my curiosity on this topic:
Java gui classes can implement hundreds of Listeners and Callbacks and many books teach you to implement all these interfaces in your gui class. Alternatively, these aspects can be implemented in inner classes, so methods called by that listeners do not get mixed up.
I'd like to know how to do this in ActionScript, which doesn't have inner classes, but has private classes. But, I don't think I fully realize what inner classes are about, so I'm merely trying to wrap my head around the situation where I would use them to organize a class' methods by their usages.
Please show an example of how this would look in ActionScript, if possible, otherwise Java.
In java it looks like that:
new JButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// code that will be performed on any action on this component
}
};
here ActionListener - is an interface, and by calling new ActionListener() {/*interfaces method implementations goes here*/}; you're creating anonymous class (anonymous because it has no name) - implementation of that interface.
Or you can make inner class like this:
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// code that will be performed on any action on this component
}
};
and then use it like this:
new JButton().addActionListener(new MyActionListener());
Moreover you can declare your listener as a top-level or static inner class. But using anonymous inner class sometimes is very useful because it allows you to implement your listener almost in the same place where the component which actions your listener is listening to is declared. Obviously it won't be a good idea if the listeners methods code is very long. Then it would be better to move it into a non-anonymous inner or static nested or top-level class.
In general, innner classes are non-static classes that somehow resides inside the body of the top-level class. Here you can see examples of them in Java:
//File TopClass.java
class TopClass {
class InnerClass {
}
static class StaticNestedClass {
}
interface Fooable {
}
public void foo() {
new Fooable(){}; //anonymous class
class LocalClass {
}
}
public static void main(String... args) {
new TopClass();
}
}
Gasan gives an excellent example of how inner classes are typically used for callbacks in Java GUIs. But in AS3 you would not normally do it this way, because AS3 event listeners are function references, not interfaces. In this respect, AS3 has more in common with JavaScript than Java.
What you can do in AS3 (just as with JavaScript) in place of the anonymous inner class callbacks is create function closures.
EDIT: I found a reference here that saves me a lot of typing:
ActionScript 3.0 using closures for event handlers

Categories