Im curious if there exists an abbreviation form for getter/setter methods of objects
SimpleObject oSimple = new SimpleObject();
oSimple.setCounterValue(oSimple.getCounterValue() + 1);
like one for simple datatypes
int counter = 0;
counter += 2;
Info
The getter/setter methods are required.
Addition
If there isn't a language feature thats support the idea, what is the most convenient way to deal with that in context of good and clean code?
You have C# background I can imagine ;-)
It's not possible in Java (apart from not-quite-the-same solutions such as having public properties etc). Same as operator overloading, which could also have solved your issue.
However have a look at http://www.eclipse.org/xtend/ though, it's a JVM language similar to Java that supports operator overloading and some other nifty things.
As geert3 said there is no shortcut to setters/getters in Java without accessing the property directly.
In your case your SimpleObject-class should just have a method increaseCounter() and maybe increaseCounterBy(int add) (or simply add(int a)).
For this case, I create annotation
/**
* Annotation for PropertiesContainer class (that has field without getter and setter)
* This class look like as class with Properties in C#
*
*/
public #interface PropertiesContainer {
}
Add add to any class (annotation shows that isn't error)
#PropertiesContainer // class without getter and setter
public Class SomeObject{
public int counter;
}
And just use:
oSimple.counter++;
If the value doesn't have to be checked for any wrong values / execute code when setting it, you could solve it by just referencing the variable directly:
public Class SomeObject{
public int value;
}
public Class Main{
public static void main(String[] args){
SomeObject o = new SomeObject();
o.value += 1;
}
}
If the example you gave is all you want to do (increment and assign an index for a new object every time you make one) then a common practice is use a static variable as a counter and a local variable for the specific index.
class SomeObject {
static int objectCounter;
private int index;
public SomeObject() {
index = objectCounter++;
// additional constructor code
}
}
If you wish to add a number to a variable, I'd consider making a separate method that does just that rather than trying to rewrite set(), or if it makes sense, make it part of the code for the set().
Related
Hello I am curious to know that Is there any purpose to make private class variable to public in Java.
public class XYZ {
public String ID;
public ABC abc;
private class ABC {
public boolean isExist;
}
}
Thanks in advance.
Yes, there's a purpose. If you do that then those program elements which can access the class can manipulate that variable directly. Otherwise (say if the variable is private), those elements would still be able to access the class but won't be able to manipulate the variable (unless you provide a getter/setter for it).
Think about it this way: the class modifier defines the level of access to the class, the variable modifier then defines the level of access to the variable itself (for those elements which can access the class).
This is sometimes done for data-only classes. For example, this is sometimes done to represent the models stored in databases (see Objectify for a real example of how this is used, in conjunction with annotations, to represent the database models that are stored in an App Engine database).
That being said, this sort of thing makes for a very poor API. If you do this, I'd suggest doing it with classes that are either package-level access or in private nested classes, only. When exposing functionality or data to code outside your package, it is generally better to do it with a carefully designed interface that would allow you to change the implementation if your underlying structure were to change.
That is to make isExist visible to XYZ class.
Note, ABC is only visible to XYZ and not to any outside classes and its variable is public so you can have access to it. private has not meaning to XYZ, only outside classes
From inside XYZ,
ABC abc = new ABC(); //can only be accessed by XYZ.
abc.isExists = true; //can only be accessed by XYZ
Making isExist public means you do not care about encapsulating (prevent it from unwanted manipulation from outside) it. If you make it private, you will need a get accessor to expose it
private class ABC {
private boolean _isExist; //only through accessors
public boolean isExist()
{
return _isExist;
}
}
You can do either of the following two things to your class instance variables:
THING # 1: Keep your instance variables private. Then have public getter and setter methods to get and set the value of that variable. The good thing about it is that you get to put checks inside the setter method. For example, lengths can never be negative. So, you can't just make lengths public and let anyone assign it whatever value they want. You need to make sure the value being assigned to it is not negative. So:
class myClass {
private int length;
public void setLength(int i) {
if ( i > 0 ) {
length = i;
}
}
}
Also, you can make your instance variables read-only, write-only, or read-and-write, depending on the availability of getter and setter methods for that private variable.
THING # 2 : If you don't need any restrictions on the value of your instance variable, and you want it to neither be read-only nor write-only, then it's fine to keep that variable public. For example: babies can have any name - no restrictions:
class Baby {
public name;
}
class Mother {
public void nameTheBaby() {
Baby baby = new Baby();
baby.name = "Sarah";
}
}
Currently I am learning basics of java and C++. I have read in book Let Us C++, that in almost every case we we make instance variables private and methods public for the security purposes. But it is also mentioned in this book that in some cases we make variables public and methods private..
I am continuously thinking, in which cases we will do so. Can anyone please explain this.
Private methods (or private member functions in C++ terminology) are mostly useful as helper functions. For example, think of the case that you want to implement fractions, but want to ensure that your fraction is always normalized. Then you could use a private member function normalize() which normalizes your fraction, and which is called after each operation which might result in a non-normalized fraction, for example (C++ code):
class Fraction
{
public:
Fraction(int num, int den = 1);
Fraction operator+=(Fraction const& other);
Fraction operator*=(Fraction const& other);
// ...
private:
int numerator, denominator;
};
Fraction::Fraction(int num, int den):
numerator(num),
denominator(den)
{
normalize();
}
Fraction Fraction::operator+=(Fraction const& other)
{
int new_den = denominator*other.denominator;
numerator = numerator*other.denominator + denominator*other.numerator;
denominator = new_den;
}
Fraction Fraction::operator*=(Fraction const& other)
{
numerator *= other.numerator;
denominator *= other.denominator;
normalize();
}
void Fraction::normalize()
{
int factor = gcd(numerator, denominator);
numerator /= factor;
denominator /= factor;
}
Another, C++ specific use of private functions is based on the fact that in C++ private is only about access control, not about visibility. This enables to do unoverridable pre-post-condition checking in the base class while making the actual function virtual:
class Base
{
public:
foo frobnicate(some arguments);
private:
virtual foo do_frobnicate(some arguments) = 0;
};
foo Base::frobnicate(some arguments)
{
check_precondition(arguments);
foo result = do_frobnicate(arguments);
check_post_condition(foo);
return foo;
}
Classes derived from Base will override do_frobnicate, while users will call frobnicate which always checks the pre/postconditions no matter what the derived class does.
Generally static final variables are public in a class. If you don't need to change the value of that variable and want other classes to access it then you make it public static final.
Private methods are used only within the class for doing the task, which is internal to that class. Like a utility method or some business calculation method. Or simply to break the code of public method into multiple private methods, so that methods don't grow too big.
When a method is to be used by other methods(public) of the class and you do not want the object to access that method directly, we make that method as private.
And in some cases, if you want to access your variable directly from the class object, then make it public.
If you don't need the varibale or methode in other classes don't make it public. This goes for methodes and variables.
private methods are for the internal use of the class. They can be called from other public classes. Those are private because you encapsualted from outer world.
For example
public void method1(){
method2();
}
private void method2(){
// for internal use
}
Public variables are mainly used for class variables in which cases there is no harm of direct accessing the variables from outside. For example
public static final int FLAG = true;
You can directly call the variable from outside.
It depends how much security you want for each class.
For example, if you have a Vector class, that only has 3 variables x, y and z, you should make them public. Many classes will probably use the Vector class and it's fine if they change values in it.
If you have a Person class that stores credit card number, background record, address etc, you should make them private to avoid security issues.
However, if you have all variables as private, and you provide accessors and mutators for all of them, you're effectively making them just like public (but with more work).
EDIT:
All constant variables should be public, because you cannot change them anyway.
Static variables could be both, depending on a situation. Probably better to have static get and set functions for static variables.
Private variables or functions can be use only in the class where they are declarated.
Public variables or functions can be use everywhere in your application.
So you should declarate private all those variables and functions that you are going to use ONLY in the class where they belong.
Example:
public class Car {
private String model;
public setModel(String model) {
if (model != null)
this.model = model;
}
public getModel() {
return model;
}
private doSomething() {
model = "Ford";
}
}
In the class Car we declarate the String model as private because we are going to use it only in the class Car, doing this we assure that other classes couldn't change the value of this String without using the function setModel.
The functions setModel and getModel are public, so we can access the private variable model from other classes ONLY using those methods.
In this example, the function setModel checks if the value its null, in which case it doesn't set the value. Here you can see that if you had declarated the String model as public, you wouldn't have control over what value it's being recorded.
The function doSomething is private and other classes can't use it. For other side, like this function is private and it belong to the same class where is the String model, it can change its value without using the method setModel.
A rule of thumb, you make methods public when it is okay for other classes to access them. internal methods or helper methods should either be protected or private.Protected if you want the method to be extendable by those extending your class however if you don't want this just mark them private.
Consider I am having the following enum class,
public enum Sample {
READ,
WRITE
}
and in the following class I am trying to test the enum class,
public class SampleTest {
public static void main(String[] args) {
testEnumSample(Sample.READ);
}
public static void testEnumSample(Sample sample) {
System.out.println(sample);
}
}
Here I am specifying Sample.READ then passing it as the parameter to the method testEnumSample.
Instead if we want to instantiate the enum class and pass it as parameter what we need to do?
Here I need to specifying Sample.READ to pass it as parameter. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?
What would "instantiate the enum class" even mean? The point of an enum is that there are a fixed set of values - you can't create more later. If you want to do so, you shouldn't be using an enum.
There are other ways of getting enum values though. For example, you could get the first-declared value:
testEnumSample(Sample.values()[0]);
or perhaps pass in the name and use Sample.valueOf:
testEnumSample("READ");
...
Sample sample = Sample.valueOf(sampleName);
If you explained what you were trying to achieve, it would make it easier to help you.
Internally, enums will be translated to something like this
class Sample extends Enum {
public static final Sample READ = new Sample("READ", 0);
public static final Sample WRITE = new Sample("WRITE", 1);
private Sample(String s, int i)
{
super(s, i);
}
// More methods, e.g. getter
}
They should not and cannot be initialized.
Enums doesn't support public constructors and hence, cannot be instantiated. Enums are for when you have a fixed set of related constants. Exactly one instance will be created for each enum constant.
Check my answer in another post.
There are 2 ways:
Use Enum.valueOf() static function, then cast it into your enum type.
Enum v = Enum.valueOf(TheEnumClass, valueInString);
Use class.getEnumConstants() function to get the list of the enum constants, and loop this list and get.
Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
// use plugin.name() to get name and compare
}
You cannot create a new enum instance. Otherwise it won't be an enum.
You can reference an already existing enum. As in your example
Sample sample = Sample.READ;
The elements within an Enum are objects that are instances of the class.
You no need to create an object of Enum.
Here is a similar issue
Refer this
You cannot instantiate an Enum, thats the whole point of having an Enum.
For example you would use enum when defining properties of some thing which would never change like:
enum TrafficLight {
RED("stop"),
YELLOW("look"),
GREEN("go")
}
private string value;
private TrafficLight(String value) {
this.value = value;
}
public getValue() {
return value;
}
Now if you want to get the value of the enum, you can use valueOf method of enums. The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though;
TrafficLight trafficLight = TrafficLight.valueOf("RED")
String value = trafficLight.getValue();
If you do TrafficLight.valueOf("XYZ"), it will throw an IllegalArgumentException
I'm answering to the first question. You can easily do it like this:
public static void main(String[] args) {
Sample.READ.testEnumSample();
}
public enum Sample {
READ,
WRITE;
public void testEnumSample() {
System.out.println(this);
}
}
Fetch a good book on Java Basics and read it.
Anyways, Enums in java are classes with fixed number of objects and objects are defined by its attributes.
Again, you can read something about it here
I'm trying to figure out the best way to create a class whose sole purpose is to be a container for global static variables. Here's some pseudocode for a simple example of what I mean...
public class Symbols {
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
/* ...and so on for a bunch of these */
}
I don't need constructors or methods. I just need to be able to access these "symbols" from everywhere simply by calling: Symbols.ALPHA;
I DO need the actual value of the String, so I can't use an enum type. What would be the best way to accomplish this?
Well, it's not clear what else you need beyond the code you've already given - other than maybe making the class final and giving it a private constructor.
However, in order to avoid accidentally using an inappropriate value, I suspect you would be better off making this an enum, like this:
public enum Symbol {
ALPHA("alpha"),
BETA("beta");
private final String value;
private Symbol(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
That way:
You can't accidentally use Symbol.ALPHA where you're really just expecting a string
You can't accidentally use a string where you're really expecting a symbol
You can still easily get the string value associated with a symbol
You can switch on the different symbol values if you need to
You can do that using an interface. No need to construct, values are public, static and final, and can obviously be strings. Such an interface would look similar to your class:
public interface Symbols {
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
/* and so on */
}
You can access the fields directly from everywhere in your code (given it's public) as Symbols.ALPHA etc.
Or, you can use an enum even though you want strings - ALPHA.toString() will return "ALPHA" (and if you want a slightly different string, you can override toString())
Are these configuration parameters or simply "constants" which don't change no matter what? For the former, I'd rather create a configuration class and instantiate it with different values for each environment. Then simply use dependency injection to inject these configurations in different classes. If your requirement is the latter or you are not using DI (Spring/Guice), static classes/interfaces are good to go.
How and where should we use a Static modifier for:
1. Field and
2. Method?
For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
But why is it a good practice?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by #duffymo, not in case of Math class).
UPDATE 1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
There is only one 'copy' of a static field/method.
Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
Static uses less memory since it exists only once per Classloader.
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
a static field exists only once. So if you have a simple class (kinda pseudocode):
class Simple {
static int a;
int b;
}
and now you make objects with:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.
Hope that clears it up a little.
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
Most of the posts above are similar, but this post might offer some other insight. When to use Static Modifiers
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
Try it:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}