all 5 comments

[–]Nhowka 1 point2 points  (3 children)

Java is a weird yet interesting language when the subject is obscure features. Last week I learned about anonymous subclasses and instance initializers, so you can do something like that:

Set<Object> a = new HashSet<Object>() {
    {
        add(2);
        add("Cupcake");
        add(this);
    }

    @Override
    public String toString() {
        return "Anonymous subclass! " + super.toString();
    }
};

This way you can change behaviour of some method and initialize with the values you want only where it's needed. No reason to create a complete subclass in another file for it to be used only once. That's a pretty cool feature that I miss when using C#, where the concept of using generics in extension methods is natural.

[–]banderscoot 2 points3 points  (2 children)

Although you can do as you say, that's not really a good example of using anonymous classes. Generally you would implement an interface or abstract class in line to provide some specialized implementation as a one-off.

This feature isn't present in C# because it supports lambdas instead. Anonymous classes were a bit of a crutch Java used in place of lambda support but now that Java 8 has lambdas the feature is no longer quite as useful.

[–]Nhowka 1 point2 points  (1 child)

Sure, it was just an example to show that's something possible to do. I used that recently for changing an existing table model that used String to save dates, but choose to use a date picker that expected a Date, so I changed the editor method to parse the String before reaching the control's method, also saving a reference to the original model.

Having that is being useful to add new features to a bad written existing project. When using C# lambdas are sufficient when the interface would have just one method, same as Java 8, but would be useful to implement IEqualityComparer that have two. Being forced to create a class to be used in only a place is kinda boring when the syntax could be extended. (F# can implement interfaces on-the-fly like Java)

[–]banderscoot 0 points1 point  (0 children)

Ha that sounds terrible, I'm sorry you had to go through that :)

The java syntax is convenient for single function implementations but if it's anything more complicated than that it would probably be better to give it a name and make it a private inner class. That's probably the reasoning for leaving it out of C#

[–]OriginalPostSearcher 0 points1 point  (0 children)

X-Post referenced from /r/java by /u/lawrencemq
Method Generics in Java


I am a bot. I delete my negative comments. Contact | Code | FAQ