I know several programming languages. Most of them are scripting languages like lua, perl, JS, ruby, etc.
But recently, I started programming in Java, which works quietly. So I have been thinking of a certain function that exists in JS. The prototype of constructors, that is. For further understanding of what my question really is, I will make an example in JS. Let’s say you want to create an application of dogs.
function dog (){
this.property1 = value;
this.propertr2 = value2;
this.propertyN = valueN;
//etc.
}
//now, I will create several instances of the constructor in JS
var snoopy = new dog();
var buddy = new dog();
and the awesome part, that I know about JS is that you can dynamically change the information of the constructor and all of the instances that is of the constructor (as it is called in JS) with the prototype keyword like this:
dog.prototype.bark = function () {
console.log("Woof!");
};
and THIS, does not only change the information about the constructor so that every dog that will ever be created with the constructor will know how to bark, it also changes so that all of the instances of the constructor gets the information of the prototype insertion which in this case teaches the dogs how to bark. which we can see in the next example:
var someOtherDog = new dog ();
someOtherDog.bark(); //output will be: Woof!
snoopy.bark(); //output will also be: Woof!
buddy.bark(); //you guessed it! it will also be: Woof!
So with this prototype keyword in JS I can manipulate constructors and their instances. Now, my question is:
HOW can I manipulate the classes and their instances in java? And is that even possible?
and if so; what should I do in order to do anything like that in java?
class dog
{
private String hairColor;
public dog ()
{
hairColor = "Brown";
}
public static void main (String args[])
{
dog snoopy = new dog ();
dog buddy = new dog ();
//now, how do I manipulate the class like I did in JS?
}
}
You can create anonymous classes on the fly if you want.
Say you have a class:
Here’s the result
Now buddy he doesn’t say woof – he says ruff! So we create one on the fly like so
Which results in
If you wanted to permanently change every dog, that becomes more difficult, but can be done via the strategy pattern.
Let’s say we have the following
Then you can do the following
This results in