Function within a function in Java [duplicate] - java

This question already has answers here:
Nested functions in Java
(8 answers)
Closed 6 years ago.
Is it possible to define a function within a function in Java? I am trying to do something like:
public static boolean fun1()
{
static void fun2()
{
body of function.
}
fun();
return returnValue;
}
but I am getting error Illegal start of expression.

The reason you cannot do this is that functions must be methods attached to a class. Unlike JavaScript and similar languages, functions are not a data type. There is a movement to make them into one to support closures in Java (hopefully in Java 8), but as of Java 6 and 7, it's not supported. If you wanted to do something similar, you could do this:
interface MyFun {
void fun2();
}
public static boolean fun1()
{
MyFun fun2 = new MyFun() {
public void fun2() {
//....
}
};
fun2.fun2();
return returnValue;
}

You cannot (and in Java they are called methods).
You can, however, define an anonymous class inside of a method, and call its methods.

Related

Calling a method in ExecuterService using double colon (::) [duplicate]

This question already has answers here:
:: (double colon) operator in Java 8
(17 answers)
Closed 2 years ago.
I have a class constitues 2 methods static and non static respectively, as per my limited knowledge submit method accepts runnable,callable instance directly or through lamba expression.
Today I came to know that we can even call or trigger static as well as non static method directly by using double colon which has been added in java 8.
I was just wondering how this works, there is no run method in my class and it doesn't implements runnable and even I'm not using lamba?
Is it a good practice to use :: or one should pass the runnable or callable instance.
Is there any other way to call a method inside submit() rather passing an instance?
Class A {
public static void printSomething(){
System.out.println("Staitc Method");
}
public void print()
{
System.out.println("Non-Staitc Method");
}
}
psvm()
{
A a = new A():
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(A::printSomething); //Expected is runnable or callable task
es.submit(a::print);
}
A::printSomething is called a method reference. When you use a method reference in a place that expects an interface like Runnable or Callable, Java automatically creates an implementation of that interface that calls the method.
That is,
es.submit(A::printSomething);
behaves the same as
es.submit(new Runnable() {
public void run() {
A.printSomething();
}
});
but is easier to read and does not create a new class everywhere you use it, or a new object instance every time it's called.
You can read more about method references in
The tutorial from Oracle
This write-up on Baeldung
Another way of achieving the same is using lambda expressions such as:
es.submit(() -> A.printSomething());
Since Runnable is a functional interface, you can use lambda expressions or method references that fit it even if the method name doesn't match. Therefore any no-arg void method can be used as a Runnable.
Runnable r1 = () -> a.printSomething();
Runnable r2 = A::printSomething(); // Method reference, short-hand
Runnable r3 = () -> A.printSomething(); // Same as r2, but as explicit lambda expression
The reason why the method reference works even though the class does not implement a void run() method is because what matters for Functional Interface assignment is the method signature and not the method names.
The method signature of A's printSomething matches Runnable's run and for that reason it works. Notice this only works with Functional Interfaces (i.e. those with only one method, said method method not having a default implementation).
Is it good practice? It's a matter of style but it is definitely not bad practice to use method references, and they're also more concise than left -> right lambdas.
I suggest you try this out yourself so you're clear on the rules.
public class FunctionalInterfaceDemo {
public static class SimpleClass {
public static void doItStatic() {
}
public void doItNonStatic() {
}
}
interface MyOwnFunctionalInterface {
void methodA();
}
interface NotAFunctionalInterface {
void methodA();
void methodB();
}
interface AlsoNotAFunctionalInterface {
default void methodA() {
}
}
public static void main(String[] args) {
MyOwnFunctionalInterface compiles = SimpleClass::doItStatic;
MyOwnFunctionalInterface alsoCompiles = new SimpleClass()::doItNonStatic;
NotAFunctionalInterface doesNotCompile = SimpleClass::doItStatic;
AlsoNotAFunctionalInterface alsoDoesNotCompile = SimpleClass::doItStatic;
}
}

got some problems with anonymous classes [duplicate]

This question already has answers here:
Declaring a method when creating an object
(4 answers)
Can I access new methods in anonymous inner class with some syntax?
(7 answers)
Override method, why can't I referenciate new own methods?
(2 answers)
Closed 3 years ago.
i was trying to create an anon class in java
class myClass {
int x = 10;
}
public class Main {
public static void main(String[] args) {
myClass myObject = new myClass() {
public void run(){
System.out.println(x);
}
};
myObject.run(); //gives an error saying "method run() is undefined for the type myClass"
}
}
and it does not seem to work at all , it gives me an error saying that method run() is undefined although i created an anon class containing the run() mehtod , i am a complete java beginner , i code most of the time in javascript , javascript is the language i am most familiar with and i am trying to get used to java concepts so yeah this question might seem silly to alot of people here and i apologize for that.
thanks in advance
This is because the compiler doesn't know there is a run method, because there isn't one on the base class myClass.
This would work in Java 10+, using var:
var myObject = new myClass() {
public void run(){
System.out.println(x);
}
};
myObject.run();
This works because myObject isn't exactly a myClass, but is actually specifically the anonymous class, which is called something like TheContainingClass$1 (where TheContainingClass is the name of the class in which this code appears).
It's a bit weird because you can't actually refer to this class by name - only with var!
Or, in earlier versions of Java, it works if you don't assign it to a variable:
new myClass() {
public void run(){
System.out.println(x);
}
}.run();
Again, this works because the receiver of the run() call has the type of the anonymous class, not myClass; but there is just no way in pre-Java 10 to declare a variable of that type.
The error occurs since your compiler is unaware of the method run()
You could fix it by making myClass an interface, or by using an abstract method.
abstract class myClass{
int x = 10;
public abstract void run();
}
If you use
interface myClass{
public void run();
int x = 10;
}
It should run. The problem here is that you don't have the run method in myClass declaration

c# Anonymous Interface Implementation [duplicate]

This question already has answers here:
C# equivalent of creating anonymous class that implements an interface
(2 answers)
Closed 4 years ago.
i've already seen this question a few times but i still don't get it.
In Java, i can do this:
new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Hello");
}
}).start();
In my opinion, this is a very nice way to implement interfaces which implementations are only used once. Is there a way to do this in C#?
I've already heard of delegates, but that only solves the problems partly since i can only implement one method. What is the "right" way to do that in C# if i have multiple methods? Do i have to implement another class for that?
Thanks in Advance!
-Chris
EDIT:
I don't want to make a new thread specifically. That was a more general question about the right way to do something like an anonymous implementation from Java in C#. It's not about that specific example.
The general way to do this is C# is to create your own private class. As you noted, other approaches in C# (delegate/lambda) only work when the interface has just one method (i.e., a Java functional interface):
Java:
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method1() { foo(); }
#Override
public void method2() { bar(); }
};
}
C#:
void testMethod()
{
x = new ISomeInterfaceAnonymousInnerClass();
}
private class ISomeInterfaceAnonymousInnerClass : ISomeInterface
{
public void method1()
{
foo();
}
public void method2()
{
bar();
}
}
Here is the simplest conversion when a Java functional interface is involved:
Java:
#FunctionalInterface
interface ISomeInterface
{
void method();
}
void testMethod()
{
x = new ISomeInterface(){
#Override
public void method() { foo(); }
};
}
C#:
delegate void ISomeInterface();
void testMethod()
{
x = () =>
{
foo();
};
}
Probably you've searched this before and by now the answer is: No. Noway in C#
But I think your main question is Why?
Short Answer: It can be designed in the next C# versions as a feature. It's absolutely possible.
Long Answer: If you want more details on why it's not added to the C# yet; there is a helpful conversation below this exact feature request in the Roslyn (an open-source .Net complier) page at GitHub. Check it out: https://github.com/dotnet/roslyn/issues/13

Java Constructor call [duplicate]

This question already has answers here:
What are all the different ways to create an object in Java?
(22 answers)
How many ways to create object in java? [closed]
(1 answer)
Closed 5 years ago.
Is there any other way to call constructor, other than new object creation from new operator?
I think when constructor chaining happens in inheritance then also constructor gets called but it does not create parent class object.
Yes and no, one way is to have your contructor call some method:
public class SomeClass {
public SomeClass() {
init();
}
public final void init() {
// do something
}
}
Then call init() again later when needed

Code Snippet involving Inheritance [duplicate]

This question already has answers here:
Using inherited overloaded methods
(11 answers)
Closed 7 years ago.
The code I am running is as follows :
public class Triangle {
public void draw() {
System.out.println("Base::draw\n");
}
public void computeCentroid(Triangle t) {
System.out.println("Base::centroid");
}
}
class RightAngledTr extends Triangle {
public void draw() {
System.out.println("RightAngle::draw\n" );
}
public void computeCentroid(RightAngledTr t) {
System.out.println("RtAngle::centroid");
}
}
public static void main(String[] args) {
Triangle tr= new RightAngledTr();
RightAngledTr rtr= new RightAngledTr();
tr.computeCentroid(tr);
tr.draw();
tr.computeCentroid(rtr);
}
The output this gives is as follows :
Base::centroid
RightAngle::draw
Base::centroid
I don't understand the reason behind the third output line.
My doubt :
tr.computeCentroid(rtr) should call the method of Derived class RightAngledTr(since the parameter passed is rtr). Hence print : RtAngle::centroid
Please help me out here. Thanks in advance!
public void computeCentroid(RightAngledTr t)
and
public void computeCentroid(Triangle t)
have different method signatures, so there is no override here, at all.
Class RightAngledTr does not override the method but overload since Java method is invariant.
Class RightAngledTr has 2 methods essentially, one requiring Triangle and the other RightAngledTr) so by specifying the most specific parameter, the JVM knows which methods to invoke by matching the parameter type to the most specific method matching it.
See more:
JLS 15.12.2.5. Choosing the Most Specific Method
For RightAngledTr.computeCentroid to override Triangle.computeCentroid it must have a matching parameter declaration. But yours does not. If you change your declaration in RightAngledTr to:
#Override
public void computeCentroid(Triangle t)
Then you will see the behavior you expect. Note the use of #Override, which will help you identify this issue in the future.

Categories