Java "Closures" comparison between Local and Anonymous Class - java

I have done some searching on the difference in implementing a closure using an anonymous class and a local class. I am trying to figure out all the differences between the two so I know which method is better in which situations.
Correct me if I am wrong:
The anonymous class has a class instance and object instance created each time a new instance is created.
The local class has only an object instance create each time a new instance is created.
Therefore, is there ever a time or place where I should use an anonymous class over a local class?
EDIT: It appears there is no real difference between the two, just depends on style and if you want to reuse the class.
To clarify what I mean here is an example of what I am talking about:
public class ClosureExample {
interface Function {
void func(int value);
}
public static void main(final String[] args) {
final Function local1 = localClassClosure("Local1");
final Function local2 = localClassClosure("Local2");
final Function anonymous1 = anonymousClassClosure("Annonymous1");
final Function anonymous2 = anonymousClassClosure("Annonymous2");
for (int i = 0; i < 3; i++) {
local1.func(i);
local2.func(i);
anonymous1.func(i);
anonymous2.func(i);
}
}
private static Function localClassClosure(final String text) {
// Local class name is irrelevant in this example
class _ implements Function {
#Override public void func(final int value) {
System.out.println(text + ":" + value);
}
}
return new _();
}
private static Function anonymousClassClosure(final String text) {
return new Function() {
#Override public void func(final int value) {
System.out.println(text + ":" + value);
}
};
}
}
Hopefully, someone can explain in detail this subtle difference and which method should be used in which situations.

This piqued my interest, and I broke out JD-GUI to look at the decompiled classes. There is actually no difference at all between the two anonymous inner classes after compilation:
localClass:
class ClosureExample$1t implements ClosureExample.Function{
ClosureExample$1t(String paramString){
}
public void func(int value){
System.out.println(this.val$text + ":" + value);
}
}
anonymousClass:
class ClosureExample$1 implements ClosureExample.Function{
ClosureExample$1(String paramString){
}
public void func(int value){
System.out.println(this.val$text + ":" + value);
}
}
Both methods are valid ways of implementing an anonymous inner class, and they seem to do the exact same thing.
EDIT: I renamed the _ class to t

I am pretty sure there is nothing like object instance, just class instance .
So yes an object is created for both local and anonymous types..
The difference however is you can't reuse the anonymous class (except through the way you used it in your method - which works but not really maintainable), so you use it when whatever you are doing is a one off thing. For example with event listeners.
I would prefer named types to anonymous types though.
You might find this useful
EDIT:
You will find my question here useful.

Just a note about this:
Therefore, is there ever a time or place where I should use an anonymous class over a local class?
If you need to quickly setup an event listener [e.g. a KeyListener] inside a component, you can do like this:
addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent ke){ ... }
// further implementation here
});
Though it won't be reusable at all.

The local class object is faster at initialization (because the class is already in memory at startup)
The anonymous class object less memory consuming (because of the lazy evaluation)
Notice : Because java is not a real functional language. Anonymous classes will be pre-evaluated and even stored in class files. So really there wont be much difference.
In a functional language, like scheme :
(define inc (lambda (a) (lambda () (+ 1 a))))
(display ((inc 5)))
The function (lambda () (+ 1 a)) will be actually recreated at each anonymous call like ((inc 5)). This is the concept behind anonymous classes.
As opposed to:
(define inc (lambda (a) (+ 1 a)))
(display (inc 5))
Where (lambda (a) (+ 1 a)) will be stored in memory at compile time, and the call to (inc 5) will only reference it. This is the concept behind local classes.

Related

How to define a method with Integer parameter (path placeholding)?

Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...

Calling a function without doing a new

I wrote a sort function and class in Java:
public class MiscellaneousUtilities {
/**
* Changes a list of "First Last" to "Last, First" and "First Middle Last" to "Last, First Middle", etc.
*/
public static Function<String, String> ToLastFirstFunction = new Function<String, String>() {
#Override
public String apply(String nm) {
String[] nmarr = nm.split(" ");
int last = nmarr.length - 1;
String res = nmarr[last];
if (last > 0) {
res += ",";
}
for (int i = 0; i < last; i++) {
res += " " + nmarr[i];
}
return res;
};
};
}
When I want to use it I can't just say MiscellaneousFunctions.ToFirstLastFunction()
I have to do a new MiscellaneousFunctions().ToFirstLastFunction;
I tried putting static in front of the class declaration but it allows only public, final and abstract. Looking at the Math class if I want to use Math.min() I don't have to do a new Math().min(). Math is also defined as a class that does not have static in front of it, and min() does as does ToFirstLastFunction, so I don't understand the difference.
That's because you have to call that function with an apply like this:
MiscellaneousFunctions.ToFirstLastFunction.apply("yourstring");
You can add an other static function as a shorthand though:
public static String toFirstLast(String str) {
return ToLastFirstFunction.apply(str);
}
The main difference between Math.min and your solution that Math.min is a regular static method while you have a Function object and those can be called with apply.
Math.min() is a a method not a function, declared like this in Math.class:
public int min(int a, int b) {
...
}
... and it is methods like this that you can invoke directly as in int x = Math.min(3,2).
You have created a public static class variable called ToLastFirstFunction -- that's not something you can call like a method. But you can do things with it using the methods in the java.util.function.Function interface -- the simplest being apply():
String out = MiscellaneousFunctions.toFirstLastFunction.apply("John Doe");
(I changed the capitalisation of your identifier -- find out about Java capitalisation conventions)
It is not the case that you can call your public static Function<...> using new MiscellaneousFunctions().toFirstLastFunction("John Doe") -- I'm not sure why you thought it was so.
You can do new MiscellanousFunctions().toFirstLastFunction.apply("John Doe") -- but your compiler should warn you about accessing a static variable via an instance. MiscellanousFunctions.toFirstLastFunction.apply() is the right way.
So the short answer to your question is: if you want to invoke it that way, write it as a method.
But if that's the case, why would you define an operation as a function, rather than a method?
Well, functions have the benefit that, unlike methods(*), they are objects -- so you can pass them around, put them in collections, assign them to variables. And they have methods like compose() and andThen() which return a new function that combines this function with another.
So you can do things like:
Map<String,Function<String,String> nameTranslationStrategies = new HashMap<>();
nameTranslationStrategies.put(
"no change", x -> x);
nameTranslationStrategies.put(
"to first-last",
MiscellaneousFunctions.toFirstLastFunction);
nameTranslationStrategies.put(
"capitalised first-last",
MiscellaneousFunctions.toFirstLastFunction
.andThen( s -> s.toUpperCase());
...
String nameTranslationOption = config.getProperty("nameTranslationOption");
String name = nameTranslationStrategies
.get(nameTranslationOption)
.apply(inputString);
Java programmers managed for decades without this feature -- functions didn't exist until Java 8. But you can do lots of neat things with them.
Even so, this isn't a reason to write your code as a Function bound to a static variable, since you can access ordinary methods as functions using the :: syntax:
Function<Double,Double> logarithm = Math::log;
double x = logarithm.apply(2.0);
Note also, that you've used a long-winded syntax to define your function:
public static Function<String, String> slimify = new Function<String, String>() {
#Override
public String apply(String s) {
return "slim says " + s;
}
}
... can be written as:
public static Function<String,String> slimify = s -> {
return "slim says " + s;
}
... or even (since this one's a one-liner)
public static Function<String,String> slimify = s -> "slim says " + s;
It's good to know the long-winded way, because it shows how functions work behind the scenes. But in real world code, the shorter form is the way to go, as it is more expressive: the intent of the code isn't hidden by clutter. This is such a quick and easy way of expressing a function, that people often use them in-line rather than assign them to a variable -- as I have done in the map example above.
(*) I said that methods are not objects. This isn't strictly true -- partly because you can get one as an object using ::, but also because you can use Java's Reflection API to access classes and methods as objects. But you don't want to use Reflection, unless you really know you need to.
Math.min() is a public static method called min, your Function is a Function object, it's not a method. Your object has a method apply and you have to use that method for what you want to achieve, like this:
MiscellaneousFunctions.ToFirstLastFunction.apply(something)

Java constructor design

I was reading an open-source code, and there was a constructor designed like this:
public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
boolean binary;
public FeatureSequence2FeatureVector (boolean binary)
{
this.binary = binary;
}
public FeatureSequence2FeatureVector ()
{
this (false);
}
}
This may be just a trivial preference matter, but what I would do is like this:
public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
boolean binary = false;
public FeatureSequence2FeatureVector (boolean binary)
{
this.binary = binary;
}
public FeatureSequence2FeatureVector ()
{
}
}
Is there any possible negative outcome by assigning an initial value for class variables?
Would the two ways be almost equally preferred?
These two ways are not equally preferred.
The original way makes sure that all initialization goes through a primary constructor. The second way allows different paths for initializing an object.
In your example it's pretty trivial. But with the second way one constructor could be modified to do something different from how the other constructor did things, whereupon how your objects are initialized depends on which constructor was chosen.
This question shows a situation where allowing different paths caused trouble.
One reason I've seen developers do this is for maintainability and future-proofing.
Let's break it down into a different application:
public void foo() {
this.foo(1);
}
public void foo(int a) {
this.foo(a, 2, 3);
}
public void foo(int a, int b, int c) {
// ...
}
foo is assumed to do the exact, or a similar, operation - regardless of the overload. However, what if that functionality were to change? In your example, you'd have to change the functionality for both versions, whereas in the above example, only foo(int, int, int) would have to be changed.
Future-proofing is something that is taken into account in the design of an API, and the above design pattern is adopted frequently due to the ability to maintain one block of code versus 2 or 3 (or however many overloads you have).
Constructors are no different, other than that they are invoked with this(...).

Does Java support static variables inside a function to keep values between invocations?

https://stackoverflow.com/a/572550/1165790
I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.
I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.
I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?
I want it to have function scope, not class scope.
I want it to have function scope, not class scope.
Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.
If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.
On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)
How are you going to keep a value between calls without "wasting memory"? And the memory consumed would be negligible.
If you need to store state, store state: Just use a static field.
Caution is advised when using static variables in multi-threaded applications: Make sure that you synchronise access to the static field, to cater for the method being called simultaneously from different threads. The simplest way is to add the synchronized keyword to a static method and have that method as the only code that uses the field. Given the method would be called infrequently, this approach would be perfectly acceptable.
Static variables are class level variables. If you define it outside of the method, it will behave exactly as you want it to.
See the documentation:
Understanding instance and Class Members
The code from that answer in Java...
public class MyClass {
static int sa = 10;
public static void foo() {
int a = 10;
a += 5;
sa += 5;
System.out.println("a = " + a + " sa = " + sa);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
foo();
}
}
}
Output:
$ java MyClass
a = 15 sa = 15
a = 15 sa = 20
a = 15 sa = 25
a = 15 sa = 30
a = 15 sa = 35
a = 15 sa = 40
a = 15 sa = 45
a = 15 sa = 50
a = 15 sa = 55
a = 15 sa = 60
sa Only exists once in memory, all the instances of the class have access to it.
Probably you got your problem solved, but here is a little more details on static in Java. There can be static class, function or variable.
class myLoader{
static int x;
void foo(){
// do stuff
}
}
versus
class myLoader{
static void foo(){
int x;
// do stuff
}
}
In the first case, it is acting as a class variable. You do not have to "waste memory" this way. You can access it through myLoader.x
However, in the second case, the method itself is static and hence this itself belongs to the class. One cannot use any non-static members within this method.
Singleton design pattern would use a static keyword for instantiating the class only once.
In case you are using multi-threaded programming, be sure to not generate a race condition if your static variable is being accessed concurrently.
I agree with Bohemian it is unlikely memory will be an issue. Also, duplicate question: How do I create a static local variable in Java?
In response to your concern about adding an additional parameter to the method and exposing implementation details, would like to add that there is a way to achieve this without exposing the additional parameter. Add a separate private function, and have the public function encapsulate the recursive signature. I've seen this several times in functional languages, but it's certainly an option in Java as well.
You can do:
public int getResult(int parameter){
return recursiveImplementation(parameter, <initialState>)
}
private int recursiveImplementation(int parameter, State state){
//implement recursive logic
}
Though that probably won't deal with your concern about memory, since I don't think the java compiler considers tail-recursive optimizations.
The variables set up on the stack in the recursive call will be function (frame) local:
public class foo {
public void visiblefunc(int a, String b) {
set up other things;
return internalFunc(a, b, other things you don't want to expose);
}
private void internalFunc(int a, String b, other things you don't want to expose) {
int x; // a different instance in each call to internalFunc()
String bar; // a different instance in each call to internalFunc()
if(condition) {
internalFunc(a, b, other things);
}
}
}
Sometimes state can be preserved by simply passing it around. If required only internally for recursions, delegate to a private method that has the additional state parameter:
public void f() { // public API is clean
fIntern(0); // delegate to private method
}
private void fIntern(int state) {
...
// here, you can preserve state between
// recursive calls by passing it as argument
fIntern(state);
...
}
How about a small function-like class?
static final class FunctionClass {
private int state1; // whichever state(s) you want.
public void call() {
// do_works...
// modify state
}
public int getState1() {
return state1;
}
}
// usage:
FunctionClass functionObject = new FunctionClass();
functionObject.call(); // call1
int state1AfterCall1 = functionObject.getState1();
functionObject.call(); // call2
int state1AfterCall2 = functionObject.getState1();

What are the implications of private keyword in java?

The following code works & runs perfectly.
public class Complex {
private int real, imag;
Complex(int r, int i) {
real = r;
imag = i;
}
public static Complex add(Complex c1, Complex c2) {
return new Complex(c1.real + c2.real, c1.imag + c2.imag);
}
public String toString() {
return real + "+i" + imag;
}
public static void main(String[] args) {
Integer.parseInt("5");
System.out.println(Complex.add(new Complex(2, 3), new Complex(3, 4)));
}
}
Now according to Object oriented design model, private instance members shouldn't be accessed through a object reference (which has been done here by c1.real ).
So, in that sense,there should be compiler error. But it doesn't object.
Now according to my understanding it's allowed because
c1.real code is written in the body of the private class Complex class itself.
Developer of Complex class should have access to all instance members [be it private,protected whatever] when accessing through an object reference, since Developer knows very well what he's doing unlike any third party. That's why object oriented model model isn't followed here.
Can anyone suggest a better explanation about why c1.real code is allowed here?
private means it cannot be access from another outer class. It is class based, not object based security. Note: classes in the same outer class can access private member of any other class in that file.
http://vanillajava.blogspot.co.uk/2012/02/outer-class-local-access.html
The short answer is that because that's the way Java defined the private access modifier.
The longer answer is that they probably assumed that strict encapsulation only makes sense above source file level, so even an inner class can access private members of its outer class (and vice versa): it simply makes no sense to hide members within the same source file. If you've got access to the source file of a class, you can easily modify any access modifiers anyway.
(Although the inner-outer class thing is achieved via synthetic accessors, but they're almost completely transparent.)

Categories