James McDowell
James McDowell

Reputation: 2768

Java equivalent of Javascript prototype

In JavaScript, you can do this.

String.prototype.removeNumericalCharacters = function(){
    ...code...
}

or

Number.prototype.addTwo = function(){
    ...code...
}
var a = 5;
a.addTwo();
//a is now 7

Is there a way to do something similar in Java? (I don't mean the actual function, just using that as an example)

An example in Java would be

int a = 5;
a.addTwo();
//A is now 7

My question is how do I define the .addTwo() method.

Upvotes: 0

Views: 1530

Answers (1)

defectus
defectus

Reputation: 1987

It's Friday so lets answer this question. I'm not going to dive into much details (it's Friday!) but hopefully you'll find this useful (to some extend).

You certainly know that Java objects don't have prototypes. If you want to add a field or a method to a Java class you have two options. You either extend the existing class and add the method/ field to it like this:

public class A {
}

public class B extends A {
   int addTwo () {...};
}

However that's not changing the parent class. Objects of class A in the example still have no method addTwo.

Second approach is to dynamically change the class (you could use things like javassist) and method/fields to it. It's all fine but to use these new methids/fields you'd have to use reflection. Java is strongly typed and needs to know about class's available methods and fields during the compile time.

Finally and that's when things get really rough - primitive types, in your instance int, are 'hardwired' into JVM and can't be changed. So your example

int a = 5;
a.addTwo();

is impossible in Java. You'd have more luck with dynamic languages on JVM (Groovy is one of them). They're usually support optional typing and allow dynamic method calls.

So enjoy Friday!

Upvotes: 2

Related Questions