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.
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!
I have got a list of constants in a class like:
public class constants{
public String avg_label ="......";
public String count_label="......";
}
While calling , is it possible to do something like this:
public class MapDialogue{
Constants c1 = new Constants();
public String mappingLabels(String node){
String text = "c1."+node+"_label";
//Is there someway of parsing this text as code
//like in unix shell scripting?
}
}
Yes, you could use Reflection. And the code would look something like this:
String value = (String)Constants.class.getDeclaredField(node).get(c1);
Although, I am kind of unsure about a couple of things:
Why are the constants in your class not really constants? (Constants are supposed to be static and final)
Why are you even instantiating your Constants class? You should be accessing them like Constants.FIELD_NAME.
You might want to take assylias's advice in the first comment and try to avoid using reflection at all times, surely there are other ways that you could do it that are less costly.
I suppose in your case, you would most likely be better of using some sort of Map
Yes, there is a way to achieve that. You can do so via the Reflection package in the Field API. The Java tutorials for this can be located here.
The basic idea is:
Field yourField = c1.getClass().getDeclaredField(yourString);
As a side note, a Constants file usually has its members as public static final. With those modifiers, you won't need to create an instance of Constants, and the values will also be unmodifiable.
I have seen much code where people write public static final String mystring = ...
and then just use a value.
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
UPDATE
Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?
final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
belongs to the class (static: no instance necessary to use it), that
won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class, and that
will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest {
static final String str = "Hello";
public static void main(String args[]) {
// str = "world"; // gives error
System.out.println(str); // called without the help of an object
System.out.println(StringTest.str);// called with class name
}
}
Thanks
The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.
static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.
Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.
final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.
public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.
static makes it uniform value across all the class instances.
It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.
final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.
You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).
Here's why:
Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.
What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar, you'll get:
I am using version 1.0
Now, you improve Foo and change the version to "1.1".
After recompiling Foo, you run Bar and get this wrong output:
I am using version 1.0
This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
public makes it accessible across other classes.
static makes it uniform value across all the class instances.
final makes it non-modifiable value.
So basically it's a "constant" value which is same across all the class instances and which cannot be modified.
With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?"
I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.
It is kind of standard/best practice.
There are already answers listing scenarios, but for your second question:
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
Public constants and fields initialized at declaration should be "static final" rather than merely "final"
These are some of the reasons why it should be like this:
Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.
Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
I think these are all clear explanations. But, Let me clarify it by giving a java inbuild example.
In java, most would have used System.out.println()
The system is a class and out is a PrintStream class.
So what java says is I will take care of the initialization of the out object(PrintStream) and keep the initialization private to myself in the System class.
public final class System {
public final static PrintStream out = null;
//Some initialization done by system class which cannot be changed as it is final.
}
You just access the println method statically without worrying about its initialization.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java modifiers syntax and format
You can put modifiers of variables or methods in any order in Java, for example:
private static final int x;
static final private int y;
Both lines of code above work fine, and both declare an integer that is private, static, and final. My question is, what is the accepted/common standard for arranging them? What order should I put the modifiers in?
See http://checkstyle.sourceforge.net/config_modifier.html (which gives links to the language specification)
The preferred order for your example is:
private static final int x;
private static final int y is probably better. It is the decreasing order of interest from outside of the class.
When you look at 'public-private' tell whether this method/variable is of any interest to any external client.
next is static. This is mostly a class context information.
Having final as last option- This information mostly needed only by class's method.
(I generally leave it my editor to sort the modifiers- it conforms to above order)
I have made the same question but with .NET, and I received a really good answer that I want to share with you: Order of function modifiers in C#
Hope that helps,
I would say is the common way would be
private static int x;
Though I am not sure were you would put the final as the common way.
If I was doing it I would probably do it the way you had it though.
private static final int x;
I was wondering if there is an easy way to declare a variable in android programming. I am still teaching myself however I haven't been able to find the answer to this question. I would like to do something like:
var1 = 'variable1';
var2 = 'variable2';
So that it can be called later in the code by its Variable.
Thank you in advance.
I suggest learning Java fundamentals first. Declaring a variable is fundamental to Java programming language (and indeed many programming languages), its not just Android specific.
You can learn Java fundamentals here.
Good Luck in your learning
What about
private static final String VAR = "string constant variable";
String var1 = "string instance variable1";
Android is basically Java so simple look for java references.
http://library.thinkquest.org/17862/jvar.htm
int a=10;
String b="kick";
char c;