Instantiating Java object with a passed in method - java

It's been a few years since I've been heavily into Java. Coming back to it I'm seeing this pattern all over the place:
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
// do work
}
});
This looks more like Functional programming to me. It's a nice pattern but how is it possible to pass a method like this? In the old days a class was a class, and once compiled there was little you could do to it.
My questions are:
Can anyone let me know what this pattern is called?
How can I write a class that can be instantiated in this way.
Are there any other useful examples of functional patterns that have made their way into Java?
What do I need to Google to read more about this?
Thanks.

This passes an anonymous class, not a method.
This is a typical pattern, not just in Swing programming, but anywhere you need (hopefully) short, "throw-away" implementations of an interface or class that doesn't need to be re-used, instead of creating a full-blown implementation.
Any class/interface can be instantiated like this, there's nothing special about it:
public interface Foo {
String foo();
}
...
public class Main {
public static void main(String[] args) {
System.out.println(new Foo() {
public String foo() {
return "plugh";
}
});
}
}
Anonymous inner classes get their own class files, too, even though their source is embedded.
In this example, a Main$1.class file will be generated for the anonymous inner class, in addition to the expected Main.class file.

The statement: new OnRatingBarChangeListener() creates a new instance of a class. The following part inside the curly braces is the definition of the class.
In this case that class in an anonymous class that implements the named interface.
Anonymous classes are classes, that are declared without a name, and thus, can not be used like regular named classes.
This pattern is very common when using listeners, that often contain only a single to a few methods that do an almost trivial task.

This is the Listener pattern. Rating bar takes an implementation of OnRatingBarChangeListener and calls its onRatingChanged method on the appropriate event.
You can use instance of any class which implements OnRatingBarChangeListener. So you can use either a named class of your own or you can pass it an anonymous class like in the example. The anonymous class in the example is effectively a unnamed class which extends Object and implements OnRatingBarChangeListener. Since the class isn't named it cannot be referenced and so the instance passed is the only instance existing.

This is called "Observer pattern". A good example for this is adding action listeners for java button or other component. For example,
myButton.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Work here
}
});
In here "myButton" is the subject and ActionListener is the observer.

Related

Difference between Interface declared in Class and Interface declared as a file [duplicate]

I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.

Can I have an empty Java class?

I'm creating a grid based game.
I need to implement a set of obstacles that take random positions within the grid.
I've created an abstract class ALifeForm, that holds the common methods for every item within the grid. Obviously, abstract classes can't be initialised, so I was going to create a new class AObstacle, which will extend ALifeForm.
Only issue is, my AObstacle class isn't specialised. All the methods it needs are within ALifeForm.
Can I have an empty class?
Is it bad programming practice? And if so, what can I implement instead?
Of course...
class AObstacle { }
(Plus whatever inheritance model you're using.) There's nothing stopping you from doing this.
Remember that a class isn't really a thing that you're defining. A type is. The class is just the language/syntax construct used to describe the type. If the type being described has no attributes or operations aside from the inheritance model, then there's nothing else to add to it.
Though you are adding one thing. You're giving it a name. It doesn't sound like much, but defining a semantic concept with a concrete name (particularly in a statically typed environment) is very important. Your type now has an identity apart from other types in the system. If things are added to it later, there's a place to add them without refactorings and breaking changes.
Well to do it you don't need to have an abstract class and a class that extends it, or an empty class(wich is possible too).
First way:
You just need to implement two classes: The class that contains the methods and the variables you need to use and the second calss that has an instance of your first class:
public class A{
public void firstMethod(){
//do your stuff here
}
....
}
public class B{
public static void main(String[] args) {
A a=new A(); //instantiate your class here
a.firstMethod();// then just use its methods
}
}
Because if you implement a class that extends an abstract class it should implement all its methods.
Second way:
Or if you want your second class to be specialized you could have :
your first class wich should not be abstract and the second one can extend it and use all its methods, and have its specific methods

Understanding Interfaces Better

As I looked at many of the interface answers from questions here, and on Google and on this video class tutorial I am looking at I have a question. I am asking here because I can't comment if my reputation is not high so hopefully this is not to redundant. I am understanding that interfaces is like psuedocode but with more of an actual way to implement your psuedocode into the program. I undertsand
public Interface someInterface{
public void doSomething();
}
is like saying we need that function in our program so lets make this interface so when we do this
public class imDoingSomething implements someInterface{ // looking at the implements someInterface
#Override // optional
public void doSomething(){
System.out.println("Doing Something");
}
}
it makes sure as I write my program I don't forget to write this function for it is vital to my program. Is this correct?
In your example you have correctly implemented an interface. An interface can be viewed as a contract that a class must fulfill. Knowing that the class has met the requirements specified by an interface allows the object to used as the interfaces type by client code and guarantees particular methods will exist with a specified signature. This can make code more abstract and reusable for a variety of types.
So if we have an interface Playable:
public interface Play{
public void play();
}
And two classes implementing Playable:
public class Record implements Playable{
public void play(){
System.out.println("Playing Record");
}
}
public class MP3 implements Playable{
public void play(){
System.out.println("Playing MP3");
}
}
They can be used in an abstract manner by a client because it knows all classes implementing Playable have a play method:
public class Application{
List<Playable> audioFiles = new ArrayList<Playable>();
public static void main(String[] args){
audioFiles.add(new Record());
audioFiles.add(new MP3());
for(Playable p: audioFiles){
play(p);
}
}
public static void play(Playable playable){
playable.play();
}
}
On a side note
Follow Java naming standards when creating classes or interfaces. In Java these types use a capital letter for each word in the name. So your example would have a SomeInterface interface and a ImDoingSomething class.
It's more easy if you see interfaces from a consumer perspective - when you have a class which uses other objects and does not care about how these objects are concretely defined but only how these objects should behave, one creates an interface providing the methods and using it internally - and everyone which wants to use this certain class has to provide access to his data through implementing the interface so that the class knows how access everything on a code level.
An interface is a collection of abstract methods[No defination]. A class implements an interface, thereby inheriting the abstract methods of the interface.With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.
You can not instantiate an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
List is interface but the instance itself is an ArrayList
Interfaces are a way of enforcing design restrictions. By declaring the type of a variable or parameter as an interface, you're sure that the instance referenced by that variable or parameter is going to have an implementation for every method of the interface. That's the basis of polymorphism.

java action listener: implements vs anonymous class

I am trying to teach myself Java and had a question that I wasn't able to answer so far. In some of my reading online I have found two ways of using action listener that seem to do the same thing. But I am trying to figure out what is the advantage/disadvantage of one over the other.
Is it better to use anonymous class like this:
public MyClass() {
...
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//doSomething
}
});
...
}
or is it best to implement at the beginning of the class like so:
public MyClass() implements ActionListener {
...
myButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
//doSomething
}
...
}
Only if your class really is an ActionListener (is-a relationship) and will be used as an ActionListener somewhere else, it should implement ActionListener.
If it is just used internally as an ActionListener, implementing ActionListener would leak implementation details to the API of the class. Use composition in that case (has-a relationship).
This is true for other interfaces and superclasses as well.
This comes down to a style thing really. Both will perform exactly the same way in code.
The separate class will tend to keep the code inside your actual method simpler, whereas the anonymous inner class brings the code for the listener implementation within the method which can make it clearer what it is doing.
There is also the case that anonymous inner classes can access final variables in the method that creates them. You can't do that with a pre-written class (although you can pass the variables into the controller).
The separate code is re-usable - so if you have the same listener in multiple places then it is the clear winner.
If you use an anonymous class, the code becomes more readable, but you may not re-utilize it.
So, I would only use an anonymous class if it's short and I'm absolutely sure that I'll not have to use it again anywhere.

How to ensure an internal interface gets defined

Greetings,
I am trying to set up a pattern where a class definition must include an internal interface definition. So for instance if someone on my team were to define a class is it possible via an interface or base class to ensure that they have to declare and define an internal interface like below? I am not concerned with the specific definition of the interface, like what methods they declare, but that an interface named Display was defined at all.
public class Foo {
public interface Display {
void Bar();
}
public void SomeMethod() {
}
}
I appreciate any insight or pointers to documentation on this subject.
No way you can do this kind of static check.
Sometimes when you just hear a question you can literally smell bad design. That is exactly that type of question.

Categories

Resources