In Java, is there a way to emulate the first-class functions in lua and python, such as here?
def foo():
print "foo called"
bar = foo
bar() #output from this line is "foo called"
Or is the only way to have a switch statement with the different methods at each case?
Edit: thank you for the clarification, what I mean to ask is is there a way to create a reference to a function, and call it as if it was the function.
Also, the goal is not to call a certain implementation of a function, it is choose which function to call, the choices of which can entirely different. The reason I want to do this is to have a more general class that does not have to be edited to add functionality. Kind of like putting functions into a collection or list.
Edit2: for anybody viewing this question for the purpose of finding an answer to it: This has to do with stacks and heaps. Java cannot do this because its methods are stored on the stack, which is much more rigid than the heap. Python, however, stores its functions on the heap, with a reference to them on the stack. Since functions are called through a reference in python, you can change the reference to them and use as desired.
The code in the question does not demonstrate pass-by-reference behavior. In fact, neither Java nor Python have pass-by-reference semantics, it's all pass-by-value.
What you're demonstrating is first-order functions: the ability to treat a function as any other value. In Java 7 and older this is not possible, although in Java 8 a new syntax for anonymous functions (called lambdas) was introduced. The lambda syntax can be used to imitate the behavior shown.
you can't simulate pass by reference for methods, for similar things use interfaces, but for objects you can simulate here
(As #Óscar López just posted as I was writing this) What you're doing is keeping a reference to a function and passing that around by value.
The "Java way" of doing this would be to use interfaces:
Interface:
public interface Printer {
public void doPrint();
}
Implementation:
public class FooPrinter implements Printer {
public void doPrint() { System.out.println("foo"); }
}
(Other implementations could be done - BarPrinter, BazPrinter, etc.)
Caller:
Printer p = new FooPrinter();
// presumably some other code here and
// probably p is passed to another function which accepts Printer (not FooPrinter)
p.doPrint(); // outputs "foo"
Related
This program compiles and runs in C++ but doesn't in a number of different languages, like Java and C#.
#include <iostream>
using namespace std;
void foo2() {
cout << "foo 2.\n";
}
void foo() {
return foo2();
}
int main() {
foo();
return 0;
}
In Java this gives a compiler error like 'Void methods cannot return a value'. But since the method being called is a void itself, it doesn't return a value. I understand that a construct like this is probably prohibited for the sake of readability. Are there any other objections?
Edit: For future reference, I found some a similar question here return-void-type-in-c-and-c
In my humble opinion this question isn't answered yet.
The reply 'Because it says so in the specification, move on' doesn't cut it, since someone had to write the specification in the first place. Maybe I should have asked 'What are the pros and cons of allowing returning a void type like C++'?
It's because of the possibility of its usage in templates. C# and Java forbid void as a type argument, but C++ permits it to allow you to write template code like this:
template<typename T, typename TResult>
TResult foo(T x, T y)
{
return foo2(x, y);
}
If void methods weren't allowed to return a void expression, this template instantiation would be impossible if TResult was void. If that were the case, you would need a separate template definition if you ever wanted TResult to actually be void.
For example, remember how in C# there are two sets of generic general-purpose delegates, namely Func<> and Action<>? Well, Action<T> exists precisely because Func<T, void> is forbidden. The C++ designers didn't want to introduce situations like this wherever possible, so they decided to allow you to use void as a template argument -- and the case you found is a feature to facilitate exactly that.
(Allow me to write the rest in a pretend-Q&A format.)
But why do C# and Java not allow a similar construct?
First, realize how generic programming is made possible in those languages:
C# and Java generics work by parsing a generic type (or method) definition and making sure it is valid for the generic constraints/bounds you have provided.
C++ templates are a search-and-replace mechanism with a powerful metaprogramming language around them. They are not required to make sense in the absence of specific template arguments -- they go from the "template metalanguage" to the "C++ language" (so to speak) only when they get their hands on actual arguments.
Why pick one approach of implementing generic programming over the other?
The generics approach maintains the nominal typing of the rest of the language. This has the advantage of allowing the (AOT) compiler to do static analysis, type checking, error reporting, overload resolution and eventually code generation once.
The templates approach is essentially duck typing. Duck typing in a nominally typed language doesn't have the advantages described above, but it allows you more flexibility in the sense that it will permit potentially "invalid" things ("invalid" from the point of view of a nominal type system) as long as you don't actually mention those invalid possibilities anywhere in your program. In other words, templates allow you to express a larger set of cases uniformly.
Okay, so what would C# and Java need to do to support void as a valid generic argument?
I would have to speculate to answer this, but I'll try.
At the language level, they would have to waive the notion that return; is valid only in void methods and always invalid for non-void methods. Without this change, very few useful methods could be instantiated -- and they would all probably have to end with recursion or an unconditional throw (which satisfies both void and non-void methods without returning). So to make this useful, C# and Java would also have to introduce the C++ feature of allowing you to return void expressions.
Okay, let's assume you have that and now you can write code like this:
void Foo2() { }
void Foo()
{
return Foo2();
}
Again, the non-generic version is as useless in C# and Java as it is in C++. But let's move on and see its real usefulness, which is in generics.
You should now be able to write generic code like this -- and TResult could now be void (in addition to all the other types that were already permitted):
TResult Foo<T, TResult>(T a)
{
return Foo2(a);
}
But remember that in C# and Java, overload resolution happens "early", rather than "late". The same callee will be chosen by the overload resolution algorithm for every possible TResult. And the type checker will have to complain, because you're either returning a void expression from a possibly non-void method or you're returning a non-void expression from a possibly void method.
In other words, the outer method can't be generic, unless:
The callee is also generic and its return type is defined by a generic type parameter that matches that of the outer method.
Overload resolution in generic types and methods is postponed until actual type arguments are made available, so that we can pick a correct non-generic method at the call spot.
What if we went with the first option - make the callee's return type generic and move on?
We could do that, but it simply pushes our problem to the callee.
At some point, we would need some way to "instantiate" some kind of void instance and optionally be able to receive it somehow. So now we would need constructors for void (although every void method could count as a factory method, if you squint) and we would also need variables of type void, possible conversions from void to object, and so on.
Basically, void would have to become a regular type (e.g. a regular empty struct) for all intents and purposes. The implications of this aren't terrible, but I think you can see why C# and Java avoided it.
What about the second option - postpone overload resolution?
Also entirely possible, but note that it would effectively turn generics into weaker templates. ("Weaker" in the sense that C++ templates aren't restricted to typenames.)
Again, it wouldn't be the end of the world, but it would involve losing the advantages of generics that I described earlier. The designers of C# and Java clearly want to keep those advantages.
Sidenote:
In C#, there is one special case I know of, where binding happens after the validation of the generic type definition. If you have a new() constraint on a T and you attempt to instantiate a new T(), the compiler will generate code that checks whether T is a value type or not. Then:
For value types, new T() becomes default(T) -- remember that C# default struct constructors aren't really constructors in the CLR sense.
For reference types, Activator.CreateInstance is called, which is an indirect constructor invocation using reflection.
This particular case is very special because, even though it has completely postponed method binding to the runtime, the compiler can still perform static analysis, type checking and code generation once. After all, the type of the expression new T() is always T and a call to something that has an empty formal parameter list can be trivially resolved and verified.
According to the Java Language Specification §14.17:
A return statement with no Expression must be contained in one of the following, or a compile-time error occurs:
A method that is declared, using the keyword void, not to return a value (§8.4.5)
...
A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:
A method that is declared to return a value
...
So, by declaring that a method is void, you are saying that it returns no value, so you are limited to using a return; statement with no expression.
I am trying to pick up the basics of Java and I am more familiar with JavaScript.
Is the following statement accurate (I just need high level understanding):
Javascript constructor function or factory function is the equivalent (i am using this word loosely here) of a class or interface in Java.
EDIT:
This is what I am reading in a Java book:
A Java program is mostly a collection objects talking to other
objects by invoking each other's methods. Every object is of a
certain type, and that type is defined by a class or an
interface. Most Java programs use a collection of many different types.
Coming from Javascript, above sounds very much like JS constructor function is similar to a class in Java where the objects properties and methods would be defined.
I know Java and JavaScript are two separate languages.
Thanks
I'd say you're close. Constructor functions (and prototypes) in JavaScript are the closest thing to Java classes that we have in JS; but they're certainly not "equivalent".
You can dynamically add or remove properties and methods to the prototype of a JavaScript constructor; you can't add or remove things from a Java class at runtime.
Example:
function Foo() {}
Foo.prototype.hello = function() { alert('hello'); };
var f = new Foo();
f.hello(); // alerts 'hello'
delete Foo.prototype.hello;
f.hello(); // throws an error
You can achieve "inheritance" at runtime in JavaScript simply by assigning the prototypes of constructor functions to arbitrary objects. In Java you declare inheritance at compile-time and it cannot be changed at runtime.
Example:
function EnglishSpeaker() {}
EnglishSpeaker.prototype.greet = function() { return 'hello'; };
function SpanishSpeaker() {}
SpanishSpeaker.prototype.greet = function() { return 'hola'; };
function Me() {}
Me.prototype = EnglishSpeaker.prototype;
var me = new Me();
me instanceof EnglishSpeaker; // true
me.greet(); // 'hello'
Me.prototype = SpanishSpeaker.prototype;
me = new Me();
me instanceof EnglishSpeaker; // false
me instanceof SpanishSpeaker; // true
me.greet(); // 'hola'
In JavaScript a prototype is simply an object. So a "class" (constructor function) can "inherit" from any plain object; thus there is a much looser distinction between "types" and "values".
Example:
function Thing() {}
var randomObject = { foo: 1, bar: 2 };
Thing.prototype = randomObject;
var thing = new Thing();
thing.foo; // 1
In Java you can define an interface which some class must implement. JavaScript doesn't really provide any such mechanism.
These are just some of the differences off the top of my head. Point is: they're similar, and you're right to draw a connection. But they are definitely not the same.
JavaScript:
function Cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " says meeow!" );
};
}
var cat1 = new Cat("Felix");
in Java:
public class Cat {
private String name;
public Cat(String name) {
this.name = name;
this.talk();
}
public void talk() {
System.out.println( this.name + " says meeow!" );
}
}
Cat cat1 = new Cat("Felix");
From source :Does JavaScript have the interface type (such as Java's 'interface')?
JavaScript inheritance is based on objects, not classes. That's not a big deal until you realize:
JavaScript is an extremely dynamically typed language -- you can create an object with the proper methods, which would make it conform to the interface, and then undefine all the stuff that made it conform. It'd be so easy to subvert the type system -- even accidentally! that it wouldn't be worth it to try and make a type system in the first place.
If you're coming from JavaScript and learning Java, there's one huge difference that I don't think anyone else has mentioned yet.
In JavaScript, a function is an object. An object can contain properties whose values can be function objects, or they can be other objects or primitive values. When you call obj.method(arguments), the semantics are to look for a method property of the object (or a prototype), and if it's a function object, to call it.
In Java and other compiled languages with OOP features, functions are not objects. If you create a new object of a particular type, the "type" information in the object refers to a list of polymorphic functions for that type. That's how polymorphism works in these languages. If you call obj.method(arguments), and method is a method that can be overridden for derived types, then the program looks up obj's type, and then looks in the function list for the type to determine which function to call. What this means, to me, is that the object's type is a key piece of information in these languages, and OOP revolves around it; while in JavaScript, the "type" of an object is quite a bit less important, since the function itself is looked up by name in the object. One can use JavaScript in a way to make it look like it's emulating the way other languages handle OOP, but it's not required, and it's not a built-in part of the language.
I think you have to keep that in mind when going from one to the other. If you try too hard to relate Java features to JavaScript features you're already familiar with, it will be confusing.
If you are new to Java, I suggest you go to amazon.com and look for a beginning book on java that has good reviews and read it cover to cover. I think this will be the best use of your time rather than reading varoius articles on Java and picking it up piece-meal. I also suggest you don't try to port your knowledge of Javascript to Java, least you make learning Java that much harder. Note there are many books you can read for Java (web) development: Java, products built on Java (JSF, Tomcat, etc), and supporting technologies (HTML, CSS, XML, etc).
This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 9 years ago.
I was asked to answer this question:
Where should I put the Javadoc specific comment notation of /** and */
if I want to tell the user specifics about a certain instance variable
or method?
I answered with:
Above the function declaration.
The answer was rejected and this was the reason:
Functions are in non-object-oriented languages. Method is the proper name.
Is this true?
Are functions found only in non-object-oriented languages?
No. There are object-oriented languages that have functions. C#, for example, is an object-oriented language but it has anonymous functions.
What are the named procedures which are members of a type typically called in object-oriented languages like Java or C#?
Typically they are properly called methods, though this differs from language to language. In Java or C# I would say "method".
In Visual Basic, for example, the distiction is made between functions and subroutines on the basis of whether or not they return a value, not on the basis of whether they are associated with a type container.
JavaScript, an object-oriented language which uses prototype inheritance rather than class inheritance, typically refers to all of the above as "functions".
Do people frequently refer to methods as functions when speaking casually about Java or C#?
Yes. Were I writing documentation or a book or a scholarly article then I would be careful to make the distinction. In commonplace parlance though everyone reasonably conversant with the art of computer programming would understand "function" and "method" to be roughly synonyms. I would not have rejected your answer.
Any answer which limits this to a specific language is inherently flawed. In addition you must also deal effectively with static methods and subroutines.
Computer science began with the term 'subroutine'. Small sections of repeatable code which could be executed arbitrarily to perform a common action. Examples are found in early programming languages such as BASIC.
Functions were the evolution of subroutines. They take arguments and may or may not return a value. They take some concepts from maths - input, translated to a given output.
With objects we need to be able to call actions on objects and we do this be exposing methods. Like functions they take arguments and may or may not return a value.
Static methods are designed to act on all possible objects of a class.
The problem is that, pure object-orientated programming leaves no scope for the definition of functions (or indeed subroutines). And languages that evolve to become object orientated often retain syntax from functions to implement methods.
In Java we resort to using 'Utility' classes to provide functions as public static methods. The Math class in JavaScript is another example of this.
In PHP we tolerate the use of the word function to define methods.
In C++ we see both functions and methods, neither demarcated. Indeed, C++ makes no reference to methods, calling them member functions.
A function is not bound to a class.
A function is something like doStuff();.
A method is like someThing.doStuff(); or SomeClass.doStuff();.
In Java, there is no such thing as a function. They are all methods. i.e.
class Test {
public static void doSomething() {...}
public void otherThing() {...}
public static void main(String[] args) {
doSomething(); //implied Test.doSomething();
}
public Test() {
otherThing(); //implied this.otherThing();
}
}
I'm trying to learn how to program on android which of course uses Java. I understand Java vaugely, but this confuses me.
A method which I view as a function (PHP being my native programming language) can seemingly be declared anywhere in a java file and still be pulled out at any other point is this so? What I mean is in PHP you have to define a function(method) to then be able to call it. So everything has to be in order.
Also is calling a function like including that section of code in your method calling it. Example being:
method 1 contains opendb command
method 2 contains closedb command
oncreate method calls method 1 then 2 does it act accordingly.
Sorry may sound dumb but I like concrete answers and not assumptions of mine.
The order in which methods are declared in java is of no importance.
Methods have no relationship to each other. You could invoke a method1 any number of times regardless of another method method2.
A sample could look like:
public DatabaseManager {
public void openConnection() {
// ...
}
public void closeConnection() {
// ...
}
}
Which you can invoke using:
DatabaseManager db = new DatabaseManager();
db.openConnection();
// do something
db.closeConnection();
A method which I view as a function
(PHP being my native programming
language) can seemingly be declared
anywhere in a java file and still be
pulled out at any other point is this
so?
Well, partially true :-). Java (like many other languages) has the concept of "visibility" of a method (functions are usually called "methods" in Java). If a method is private, it is only visible (and usable) inside the same class, if it is public is can be called from anywhere. See e.g. the excellent Java tutorial, which covers this: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
However, unlike PHP, the order in which methods are declared inside a single class is irrelevant. You can call a method from the same class before the point/line of its definition.
Also is calling a function like
including that section of code in your
method calling it. Example being:
Yes, in the simplest case calling a method behaves like including that code in the place where the method is called. But there are important differences:
If you call a method, it cannot access local variables from the calling method, and class fields only if both methods are in the same class.
Java (being object-oriented) has polymorphism: You call a method on an object instance, and the method that is actually executed depends on the runtime type of the object instance, which may be different for different code paths. In that case calling a method is more complicated than just replacing it with the method's code.
Java methods can recursively call themselves; that wouldn't work if the compiler just included them where they are called.
So it's probably not really helpful to think of method calls as "like including the code"...
Your problem is not Java at all. It sounds like you have never programed the object oriented way. You should learn what a class is, what a method is.
I strongly recommend the basics for OOP itself: http://download.oracle.com/javase/tutorial/java/concepts/
In Java, your methods can be declared in any order in the class, for example
class A {
void C() { }
void B() { C() }
}
Could be equivalently declared as
class A {
void B() { C() }
void C() { }
}
Your second question is not very clear. But just to clarify - there is nothing like including in Java to execute another script - generally you will create new objects or run static methods of a class to accomplish things.
Max... I have not coded in PHP, but I have done a lot of scripting. According to the online docs that I found, PHP does not natively support events. So you are right, everything has to be "in order" in PHP. So you may need to get your head around moving from the sequential model of programming that I grew up with, and move to the event driven model used in Android Java.
You can divide your program into three parts. A view or presentation (main.xml). The controller or event handler (MyApp.java) and the algorithms, say model.java. MyApp.java has "event handlers" that basically sit around waiting to receive events so that you cannot absolutely know the order in which methods will be called. Do the heavy work in Model.java and write it so that it knows nothing of the view and is reusable.
So in UNIX model is the ENGINE and the view and controller is the INTERFACE. INTERFACE-ENGINE vs model-Controller-view.
Hope that helps,
JAL
I'm designing an API (in Java) and expect to have users accessing the API from Matlab. The problem is that I want the API to provide a piece of functionality like:
javaApi.waitUntilPredicateIsTrue(Predicate<JavaObj> test);
My API (in the background) gets hold of instances of Java Obj (via some mechanism, e.g. polling). I want this API method to block until one of these instances, when passed to the Predicate evaluates to true. If I was calling this API from Java, I'd do:
javaApi.waitUntilPredicateIsTrue(new Predicate<JavaObj>() {
public boolean evaluate(JavaObj jo) {
return "READY".equals(jo.getState());
}
});
You get the idea.
How can this be called from within Matlab? Can I use anonymous inner classes from Matlab? Can I declare a Matlab classdef which extends the interface Predicate (can this cope with the Java generic version)?
That sounds like a tough question. I'm still running R2006b so this may have changed, but it looks like MATLAB will not translate function handles (incl. anonymous functions) and structures into Java objects. I don't know about MATLAB custom classes, since the syntax has changed. Strings, arrays, and cell arrays will translate properly. They don't comment at all on implementing interfaces. (:p :p :p BOO HISS)
edit: just found this page on Matlab Central, it talks about some undocumented interfaces.
Matlab has a much nicer solution than forcing users to create a whole class just to provide a single method. Take a look at their anonymous functions.
Note that anonymous functions in Matlab have odd scoping rules. Make sure you read the "Variables Used in the Expression" section of the linked help page. If you want more traditional lexical scoping, take a look at nested functions.
EDIT:
I am assuming that you will be doing the polling from Matlab, not passing the predicate function to Java. Example:
function waitForPredicate(pred)
while pred
end
end
waitForPredicate(#()javaApi.isMyConditionMet());