0

I am trying to understand generics and interfaces and I came across this code:

Func<Integer, Integer> fDouble = new Func<Integer, Integer>()
{
    public Integer apply(Integer x)
    { 
        return x * x;
    }
};

I understood that the method fDouble returns the double of the inputted integer, however, I cannot understand how there is a ; after the } and how the method is declared by

Func<Integer, Integer> fDouble = new Func<Integer, Integer>()
2
  • The method fDouble returns a Func. Commented Dec 27, 2013 at 15:47
  • Wow, that's a bad name for the "variable" fDouble. Whoever wrote that should be forced to do 20 pushups, then rename it. :-) Commented Dec 27, 2013 at 16:05

3 Answers 3

2

The code is creating an anonymous class which implements the Func<Integer, Integer> interface. The supplied link is a Java tutorial which should help you understand the syntax.

The ; is there because the code is declaring a variable fDouble and storing in that variable a reference to a newly-created object of the anonymous class.

Sign up to request clarification or add additional context in comments.

Comments

2

This is actually a case of an anonymous class, which is a way to create a class without giving it an explicit name. An anonymous class can be created by extending a class or by implementing an interface. The syntax for an anonymous class that implements an interface is:

MyInterface object = new MyInterface() { 
    /* override or implement methods here */
};

The semicolon is required, like it is required after every statement in Java.

4 Comments

I get it thanks :) Now this is in a main method, if I had to do a separate class for it, how would it be changed?
In that case you would declare the class with class Square implements Func<Integer, Integer> { ... } and then use it normally: Func<Integer, Integer> fDouble = new Square();
Yes, in that case the class would not be anonymous, it would be called Square.
How do you call it from the main method if you need to use the fDouble method then?
1

Actually, it is called Anonymous inner class. Also, it is better to specify like this:

interface Func<T extends Number>{
       T measureShape(T t);
}

Because if you work with data which can be any type from Number interface, you should use bounded type. So now, you can use it with Integers or Double. Also anonymous class just implements Func interface and creates it's instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.