I know for a fact that static variable is used for all instances of the object whereas the instance variable is used specifically for each instance.
However, what if we declare the instance variable in the beginning and dont touch it in the constructor ? It will act exactly as a static variable right ?
So why bother using both of those ? I'm so confused.
"if we declare the instance variable"
... then it still is an instance variable even if you don't change it in the constructor. As the name says instance variables are for an instance only, i.e. each instance has its own copy which may have the same value. A static or global variable is only one copy that all instances have access to.
Let me make a real world example:
Several people (instances) are in a room and want to get the news.
Instance variables: everyone gets a newspaper and may chose to read it at their own pace or not at all.
Static variable: a TV in the room. Everyone gets the same channel so if anyone switches the channel all others will be affected too.
... and dont touch it in the constructor
Whether you update a variable in the constructor or not doesn't make a variable an instance variable or a global one. It's how they are declared.
Note that you could have instance variables that are changed by other methods only which is perfectly fine in many designs.
Also note that you could change a global variable in a constructor too albeit that wouldn't make much sense in many cases - but there are valid cases.
Static variables can be used without instantiating an object. You can access these without calling class constructor. Instance variables are accessed globally within the class and if you want to use them they have to be public and you must create new object by calling constructor
Related
I'm trying to understand the usage for getter/setter methods in a class. Let's say we have a class called A with some public instance variables followed by a constructor with parameters where arguments were passed from another class(main) to it. Inside the constructor we let those instance variables equal what was passed.
Now if this class were to be used by another programmer, nothing would stop them from directly accessing/changing the instance variables to something that isn't valid. By making the instance variables private we can eliminate access to those variables. However if we wanted to have those instance variables updated/changed indirectly or under some specific condition or perhaps just letting the person have access to the instance variable, we would create a getter/setter pair for this purpose.
Benefits?:
1.Change instance variable only under certain valid reasons under the set() method
2.So that we can show what the instance variable actually is without giving the programmer who is using this class the ability to change it.
Is this a correct interpretation?
Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying
member variables as private can hide the variables and methods. Objects should hide their inner workings from the
outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in
an unexpected way, which in turn makes future development and refactoring efforts easy.
Being able to encapsulate members of a class is important for security and integrity. We can protect variables from
unacceptable values. The sample code above describes how encapsulation can be used to protect the MyMarks object
from having negative values. Any modification to member variable vmarks can only be carried out through the setter
method setMarks(int mark). This prevents the object MyMarks from having any negative values by throwing an
exception.
Your interpretation is correct. Also (off the top of my head):
It allows the implementation of the class to change (eg if you wish to remove the field and replace it) without forcing consumers to interact with your class any differently.
It allows AOP frameworks to intercept calls to your get / set method.
You can specify permissions via annotations for access to methods.
Yes, your interpretation is correct. But it's because limits of language. For instance in python you don't need write everytime getter or setter, because you can override behavior of member variables. For example:
class MyClass:
def __init__(self, myproperty):
self.myproperty = myproperty
And if everybody use it in way like:
print(new MyClass("test").myproperty)
you can still change behavior of you getter:
class MyClass:
def __init__(self, myproperty):
self._myproperty = myproperty
#property
def myproperty(self):
return self._myproperty + " changed behavior"
or even of setter without touch code what use you class:
#myproperty.setter
def myproperty(self, myproperty):
if len(myporperty) > 0:
self._myproperty = myproperty
See property reference for better example.
if an instance variable is to be used only by methods defined with in its class, then it should be made it as private.If an instance variable must be within certain bounds, then it should be private and made available only through accessor methods[getter as well as Setter] Methods.
Why we can't use access specifiers for variables declared inside method in a Java Class?
Because it doesn't make sense. Variables declared in a method are local to the method; i.e. they can't be accessed outside the method. What would modifying the variable's declaration achieve?
It would make no sense to do so.
A local variable (one declared in a method) is only in scope during that method - what would it even mean to declare that as "public" or "protected"? Only code within that method is going to know about it, and it's not like you're going to differentiate between different bits of code within that method to allow some parts to access a variable and others not.
Access modifiers make sense only when you want to control how other classes use it. How would you like to control accessing a variable within a method by using those modifiers? That would sound absolutely silly controlling access of variables within a method, especially when the variable scope is only within the method. Once the method completes, the variable will have no existence. Even if the variables are allocated memory from the heap, still, once the reference is gone, the memory is available for garbage collection.
There is no sense of applying access modifier as the local variable access scope is restricted to the method scope. Hence there is no meaning of applying access modifier.
class Foo{
public void stuff(){
private String x=2; //compilation error.
}
}
The above code will not compile if we explicitly apply access modifier.
As per the rules of java whatever the variables declared in the scope of method are not accessible outside, which itself means the variables are themselves private, protected and ofcourse we know its default if none specified. so there is no point in declaring a local variable with above mentioned access modifiers. However , you can still use "final" access modifier for the reason that you don't want it to be changed during the course of the method() because of some processing like unwanted reassignment of value to the variable etc.,
Variables that are declared within a method or a block or a constructor are known as Local variables.
Local variables are initialized within the method/block and are destroyed once the method/block execution is completed.
So, specifying the access modifiers for those type of variables doesn't make any sense.
I was reading Code Conventions for Java from http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#587.
In that, they have mentioned that we should avoid the use of objects to access a class variable or a method and should we use the class name instead.
Avoid using an object to access a class (static) variable or method.
Use a class name instead. For example:
classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!
Is there a particular reason for this in terms or performance or something else?
By class variables I assume you mean static variables.
The use of static variables/methods through instance variables should be avoided because it's confusing to the reader. Since you can only use instances to access instance variables, reading a code that calls static methods through an instance can confuse the reader about what's going on.
Image this case, with Thread.sleep, which is a static method:
Thread.sleep(1000);
Since the method is static and we are calling it through the class name, it's intuitive to the reader to deduce that the effect is to put the current thread to sleep.
Now if we did this:
Thread t = new Thread(...);
t.sleep(1000);
Now which thread is put to sleep? The current one "obviously". Someone not knowing about how sleep works might think that the child thread is somehow put to sleep.
I guess it depends on what you want to do.I for one always use the class name to acces a static variable.Being static it doesn matter the way you do it, but i does save some memory usage.
As for nonstatic variables, always use objects.
It is not any different in terms of the bytecode that's produced, so performance is not the issue.
What is the issue is that using a variable to access static members looks as if the reference held by the variable actually matters to what is being accessed. But it does not! In fact even if anObject where null, you would not get a NPE, but it would just call classMethod.
So the principle is simple: when accessing static members, avoid mentioning information (in this case the variable name) that's actually not relevant to the access being made.
I don't know about performance, but clearly another developper looking your code will know at first sight its a static variable/method if you use it with the classname.
I don't think compiler will give different code using a variable though.
it's because.
1.It tells that the variable or method is a static actually.
2.Also, its checked that the object refers to which class. that incurs extra cost.
Method-Local inner class cannot access local variables because the instance of the method-local inner class may still alive after the method is over. But local variables will vanish once the local method is over.
I learned that method-local inner class can access final local variable, does this mean final local variable still alive after the method is over?
Sort of. Java anonymous inner classes act like "closures," that is, they "close" around the current local state. However, Java only lets these classes close around final variables. If it didn't, the local state of the variable could change, but the version held in the inner class would not, so it would be accessing an "out of date" instance. This could be confusing to a programmer.
Instead, Java requires that mutability be handled by the instance through methods, not variable reassignment. This leads to better clarity and allows for simpler debugging. For more information about why Java does this, see this answer.
Since the class still holds a reference to the variable, the answer to your question is yes, that instance will not be garbage collected until the inner class relinquishes ownership of the variable.
No it doesn't. It means that a copy of the local variable is still alive, in the inner class instance. The 'final' just makes sure the two copies don't confusingly diverge in value.
First of all this is NOT an exact duplicate of Initialize final variable before constructor in Java. It is probably related, but there aren't any answers that satisfy me.
My problem is about final variables in Swing GUI's. It's about custom Actions in particular.
I have a number of final variables and a number of static final variables.
The question is: if the variable is actually a constant, what is better: initialise them at construction-time, or initialise them at declaration?
The answers on the question I mentionned above generally point towards making the variable static as soon as you are able to assign it when you declare it. That doesn't really make sense to me, as the variables aren't used in a static context. I have a couple of Images that my form uses like icons, I made those static because an Image simply is a static thing unless your application modifies them. That makes sense.
On the other hand, the Actions are new instances of a custom inner class. Very technically they are static too, but it just feels different. They simply mustn't be available in static context imo. So do I put:
private final CustomAction customAction = new CustomAction();
Or do I initialise it in the constructor? Which is better? Or am I thinking the wrong way about static?
If the field is a constant, make it a static final member of the class,
public class Foo{
public static final int BAR = ...;
}
Otherwise, initialize the field in the constructor.
Initialize your constant variables at declaration: it is more readable. Make it static if it does not make any sense to put different values into it for different instances of the class, that is, if it is a class level variable, not an instance level.
I think you're on the right track with not making it static, because it sounds like your CustomAction objects are truly custom to the instance of the GUI that creates them in its constructor. I think whether you initialize it in the constructor or not depends on whether your constructor could initialize a CustomAction differently based on the constructor's input arguments.
Where static versus non-static is concerned... a good rule of thumb is, if a variable is going to remain constant across all instances of a particular object type, then that variable should be static. This saves memory over the runtime of your program and also saves CPU time when each object instance is constructed, since that constant won't have to be initialized every time you create a new instance of your Object. On the other hand, if a variable is going to remain constant for a particular instance of an Object, but may be different from instance to instance, then it shouldn't be static.
Finally (pun intended), final should be used whenever you don't want a primitive value or reference to an Object to ever change. The static or non-static context doesn't really influence whether a variable should be final, it's strictly final because the developer doesn't ever want to change that variable. Its static context depends solely on how the developer wants it to be accessed.
For a fast application startup and program parts the user possibly does not visit (About dialog), static is not good. In general static is not very liked as you did find out. There are some reasons, but nothing very convincing. But sometimes it is a anti-pattern or a sign of it.
Still in your case I would refrain from static images. By the way resources are cached internally.