I'm reviewing some Java code written long ago and not being a Java developer, I have a question. I found the following lines in the body of a class. Someone is creating an instance of SearchQueryParameter however there are curly braces following "new SearchQueryParameter" and it appears that someone overrode some functions here.
My questions are the following.
1) Are these functions overwritten at an instance level?
2) Does this language feature have a name?
public static final SearchQueryParameter X_POSTDOC_WORKFLOW_STEP = new SearchQueryParameter(128,"XPOSTDOCWorkflowStep",AdvancedFields.X_EVENT_POSTDOC_WFSTEP,SearchTypes.XEVENT_DOCUMENTS) {
#Override
protected int getFilterType() {
return SEARCH_FILTER;
}
<<snip>>
};
Thanks, mj
Background:
This is called anonymous class. It is a class that extends a non final class or implements a single interface and you're creating a single instance of this class.
Now, to your questions:
1) Are these functions overwritten at an instance level?
No, they are at level class. You have a new subclass of the desired class and this subclass overrides the method. Then, you create a new instance of the subclass.
2) Does this language feature have a name?
Yes, it is anonymous class.
You probably should have done some research on your own first, but that is called an anonymous inner class.
The code creates an instance of an anonymous class (SearchQueryParameter) and then overrides one method in it.
Essentially, it creates something that extends the SearchQueryParameter class and which overrides the getFilterType() method.
Since only one instance of this particular class definition can ever be created (without reflection), the function may appear like it's being overridden at an instance level but is actually getting overridden at the class level (since it may replace the existing definition).
It's called an anonymous class.
Related
I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.
Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.
You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.
The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!
I have a question about Java.
I have a class Say.java that has some methods, like sayHello(), saySomething(), sayBye(), ...
I have other classes too. I have a class Person, and two subclasses of Person: Senior and Junior.
My job to do is the following:
I have to set the Say.java class to be private, and create a public class SayFactory.java, with a method called getInstance. Then, to create a new instance of the Say.java class, I have to call my getInstance method with one argument: an instance of either Senior.java or Junior.java. If I create an instance of Say.java using a Senior.java object, I must be able to access all of the methods of Say.java. But if I do the same thing with Junior.java, I should be able to access all of Say.java's methods EXCEPT saySomething().
Can someone please explain how to do this and how it works?
Apologies by the way - I'm from Spain so my English isn't that great. If you don't understand the question, let me know and I'll try to write it out more clearly.
First refer to this as answer to making a class private: Java: Why can we define a top level class as private?
For the objects that you want "private" you will have to make all the fields and possibly methods of it private (depending on what you need). Then as #user1071777 mentioned set up public getters and setters.
Some basic information on calling methods of an object:
http://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
To create the connection between classes you can have a class have another class as part of its definition and set it up through constructor or public setter.
I know that I can't write Private Class but I can do a inner class.
I have a class SayFactory and within this I got another called Say
The SayFactory have a method called getInstance(), and in this method I create an object of Say class and return this object. The problem is, how to deny access to method saySomething() if the parameter of getInstance() is a object of Junior.
In Java, the standard way to create an object is using
MyClass name = new MyClass();
I also often see the construct
new MyClass() { /*stuff goes in here*/ };
I've been looking online for a while and can't find a good explanation of what the second construct style does or how it does it.
Can someone please explain how and why you would use the second construct?
This construct makes actually two things: 1) It declares an anonymous class which extends the class you use in the constructor and 2) creates an instance of this anonymous class.
Edit: When using such a construct you can observe the anonymous class by looking at the generated .class files. There is the normal MyClass.class file and another one for each anonymous subclass: MyClass$1.class for the first and so on.
You would use the second construct in the case that you want to make an anonymous class. if you have a method that takes a callback as an argument, you might want to specify the implementation of the callback inline as opposed to giving it a name and putting it in a separate file or declaring it elsewhere in the same file.
There's also a trick called double brace initialization where you can get around not having syntax for literal maps and lists by using anonymous classes, like this:
Map map = new HashMap() {{put("foo", 1); put("bar", 2);}};
Here the nested braces create an instance initializer. The object bound to map is not a HashMap, its class is an anonymous class extending HashMap. (That means if you have a PMD rule about classes needing to declare serial uids then it will complain about this.)
Double-brace initialization is a fun trick to know but don't use it in real code. It's not safe to pass around the map created like this, because the inner object keeps a reference to the outer instance so if anything in the program holds onto a reference to the map it keeps the outer object from getting garbage-collected. There are also problems with serialization.
As others have already said, it creates an instance of an anonymous class, subclassing Class. Here's an example how it is commonly used:
panel.addMouseListener(
new MouseAdapter () {
#Override
public void mouseEntered(MouseEvent e) {
System.out.println(e.toString());
}
}
);
The above code creates an instance of an anonymous class which extends MouseAdapter. In the anonymous class the method mouseEntered has been overridden to demonstrate that the anonymous class works basically as any other class. This is very convenient and common way to create (usually simple) listeners.
Second construction creates an instance of anonymous class which is a subclass of Class.
If you want to new a object by a protect constructor from another package, you can use:
new Foo() {};
otherwise you will get an access error. It equals anonymous subclass inherited from Foo class.
From jdk8 onwards you may have seen different syntax seems like creating an objects while using lambda expressions.
NOTE: Lambda expressions don't get translated into anonymous inner classes, they use invoke dynamic that was introduced in Java 7 to execute functional methods.
For Example:
public class LambdaSample {
public static void main(String[] args) {
//If implementation is only one statement then {} braces are optional
Runnable oneLineImplRunnable = ()->System.out.println("This is one line lambda expression");
//Multiple statements in the implementation then {} braces are mandatory
Comparator<StudentTest> stdComparator = (StudentTest s1,StudentTest s2)->{
if(s1.getFirstName().equals(s2.getFirstName())) {
return s1.getLastName().compareTo(s2.getLastName());
}else {
return s1.getFirstName().compareTo(s2.getFirstName());
}
};
}
}
I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".
It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).