What is the difference between class variables and member variables in Java - java

There is not much to explain. The title is enough to explain the question. I got this on an interview today.
What are class variables and member variables in Java?
Thank you!

As Zhuinden said they probably meant static variables instead of class variables. For member variables, an instance of the class is needed in order to access the variable. For example if I had a class Foo, and it had a member variable int bar, the only way I could access it is by doing something like
Foo foo = new Foo();
doSomething(foo.bar);
However, if I have bar was a static variable, that means that I can access it even though I don't have an instance of the object. I would access it like this:
doSomething(Foo.bar)
without having to create an instance of Foo.
See here

A member variable is one per object, every object has its own copy of instance variable while a class variable is one per Class, every object of that class shares the same class variable..
A class variable also called as static variable is initialized when the JVM loads the class probably take an example static block if there is no main method in your program while this is not the case with your member variables.
Class variables should be used when you don't want to have copy for each instance while
member variables should be used when you want separate copy for each instance of object.
From point of garbage collection class variables have a long life as class variables are associated with the class and not individual instance.
class variables are cleaned up when the ClassLoader which hold the class unloaded. This is very rare..while in case of member variables they get cleaned up when the instance is cleaned up. Hope this helps.

Related

How can class name without object be used to access its contents in java?

JMenuItem print = new JMenuItem("Print");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
I'm new to java. I have learned that if we want to access the contents of class then we have to first create an object of that class. Then we can use that object to access the class's contents.
But here KeyEvent and ActionEvent are classes and they can access their fields VK_P and CTRL_MASK without the help of any object. How is this possible?
Static variables, or variables initialized with a static keyword, are able to be accessed without instantiation of a class object since they are not tied to a particular instance of the class but the actual class itself.
You can access a class's variable without via an instance of that class if that variable is static.
Static variables, or variables declared with a static keyword, are class level data members
NOT instance/object level.
This means - the same static variable is common to all instances of the class and they all can access it (!!).
public class Perrson{
public static int personCounter;
mean:
you can access personCounter as Person.personCounter++ for instance..
However, when you have Person instances p1, p2,...
p1.personCounter++
p2.personCounter++
access the same variable !
It is good for example for object counter when Person constructor advances the counter.
by yl

What is the difference between a variable declared in a method and a field declared as a class variable?

Im studying for an exam and im stuck at one question that i cant figure out.
The question is: ''What is the difference between a variable declared in a method and a field declared as a class variable?''
Can someone enlighten me please?
As other people commented this is a basic stuff with variables in a programming language. In java there are types of variables, namely:
Local Variables
Instance Variables
Static Variables.
The variables declared within a method is called a local variable. The life of this variable is inside the method and is not accessible when the method is executed. These variables need to be instantiated when they are declared.
On the other hand, the variables declared outside the method but inside the class are called as Instance variables. These variables become accessible when an object is created for the class. The life of the variables is dependent on the life of the object.
Finally, static variables are same as instance variables but with the "Static" keyword. By the concept of static, they are created when the class is loaded. These can be directly accessed using the classname or the object reference. Only one set of static variables are created for every class. But in case of instance variables, each time you create an object, a set of instance variables are created for that object.
You can find a lot of online resource for this topic, I suggest you refer http://www.geeksforgeeks.org/variables-in-java/.

How static object(in another class) is still available even though it is not referred? [duplicate]

I'm reading Java tutorials from the begining and I have a question about static keyword on fields or variables. As Java said here:
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.
With that, I guess that if you have an object (in this case, an instance of the class Bicycle) and a field inside of it that its static then, independently of if you are refearing to bicycle1 or bicycle2, the field that its static will have the same value. Am I wrong or I understand it well?
I mean, if I have:
Bicycle bicycle1 = new Bicycle();
Bicycle bicycle2 = new Bicycle();
and in the class Bicycle I have a static field like:
class Bicycle{
static int gears;
//Methods to set and get gears
}
And in the bicycle1 I set the value of gears to seven:
bicycle1.setGears(7);
then if I try to get the value of gears in bicycle2 I should get the same value as I set on bicycle1, right?
System.out.println(bicycle2.getGears()); //7
Well, here is where I have the doubt because as Java said in the quote that I put above:
this tells the compiler that there is exactly one copy of this variable in existence
Where is this copy stored? How the objects access to that copy? When is this copy created?
Where is this copy stored?
The copy (static variable) is stored in the Permanent Generation section, but if you use Java8 the Permanent Generation section no longer exists.
The static variables and static methods are part of the reflection data which are class-related data and not instance-related.
How do the objects access that copy?
Every instance of class (object) that you have created has a reference to the class.
When is this copy created?
It is created at runtime when the class is loaded: this is done by the classloader of the JVM when the class is first referenced.
Static variables belong to the class, and not to instances of the class.
Your intuition is right - you have only one copy regardless of how many object you create.
You can access a static variable using the name of the class, like in this example:
class Static {
static int staticField;
}
public class UseStatic {
public static void main(String[] args) {
System.out.println(Static.staticField);
}
}
The static fields are useful to create some kind of class constants.
Finally, to easily initialize a static field of a specific class you can use Static Initialization Blocks.
Sources: University course on java, java official documentation
With that, I guess that if you have an object (in this case, an
instance of the class Bicycle) and a field inside of it that its
static then, independently of if you are refearing to bicycle1 or
bicycle2, the field that its static will have the same value. Am I
wrong or I understand it well?
When you instantiate a class in Java for the first time, the JVM creates two things:
an instance. A set of non-static fields is allocated onto the heap for each of the instances that you create. These instance fields are separate from all other instances (and are used to represent their object's state).
a Class object. Every class in Java has one, and only one, Class object ... no matter how many instances of it that are created. For example, the Class object for class String is Class<String> (which is expressed as a literal as String.class). You can think of the static fields of a class as belonging to the Class object. The lifecycle of Class objects is independent of the lifecycle of class instances; Class objects exist for as long as the JVM process is running (therefore, their static fields also exist that long).
Since a class has only one Class object, and since all instances of a class share that same Class object, the static fields of a class are shared by all the class instances that exist.
In general, it is useful to think of the static keyword as meaning "independent of any instance":
a static field belongs to the Class object and not to any instance
a static method is invoked through the Class object and has no direct access to any instance
a static member class instance is not dependent on any other instance
static variables in java are stored in the class, you don't need to create a instance of it to access them.
class Bicycle{
public static int gears = 7;
//Methods to set and get gears
}
You can access the static method like this
Bicycle.gears;
So, there's just one Bicycle class declared on java, when you instantiate a class it's create one instance of bicycle with all static attributes declared.
Where is this copy stored?
Static variables are stored in some static storage (in permgen, I believe), you should not bother about it.
When is this copy created?
They are created when class is accessed first time (loaded by class loader) and never deleted (unless class is unloaded)
How the objects access to that copy?
Instance has reference to its class, and class has reverence to all its variables. How exactly C structures are laid in memory is implementation-specific detail.
Since static vars are bound to class, not instance, you do not even need to instantiate class to access them. MyClass.myStaticVar is ok.

Is a final variable instantiated everytime

When we have a final instance variable of a class, is it instantiated for each object created of the class or just created once and referred?
And what is the case if the final variable is a local class variable??
The final modifier simply indicates that the variable can be assigned once and never again. It has no impact on the instantiation; the rules are the same as for normal variables. All the final modifier does is prevent the value being assigned a second time.
Examples below.
private final List myList = new ArrayList();
The list will be instantiated each time this is run, i.e. each time the enclosing class is instantiated.
public void bob() {
final List myList = new ArrayList();
}
The list will be instantiated each time this is run, i.e. each time the method bob is invoked.
private static final List MY_LIST = new ArrayList();
Again, the list will be instantiated each time this is run. As this is also a static field initializer, this code will be run when the class is first loaded. So, for simplistic programs, this will be run once -- in scenarios where multiple class loaders are in play (e.g. app-servers etc), however, this will be run once each time the class is loaded in a new class loader.
Final variables is instantiated for each instance of the class. The values once assigned to them may not be changed. These variables may be initialized once, either via an initializer or an assignment statement.
What you are referring to are the static variables. These variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.
Taking these two together, you can have a static final variable for the class. This basically means that the value assigned to the variable once assigned is constant and that it would be attached to a class rather than an instance of the class.
Instance variables, class variables, and local variables are used to refer to three different things, so calling a variable an "instance variable of a class," or "local class variable" is confusing.
An instance variable belongs to an object. Whether it's final or not, space is allocated in every instance for it. If it's final, a value must be assigned during construction, and the variable can be assigned only once.
A class variable belongs to the class as a whole. There's only one variable, regardless of the number of objects of that class, and all instances can refer to it. Declaring a variable as static means that it belongs to the class. Like instance variables, a static class variable can be declared final. Then it must be assigned a value once and only once when the class is initialized.
A local variable is declared within a method, and the variable occupies space in the method stack frame—although that variable may hold a pointer to an object in the heap. Local variables can be final, which means they can be assigned only once. Also, if a local variable is final, it can be referenced by inner classes instantiated in the method.
Variables are not the ones that are instantiated. Classes are instantiated. Variables are initialized. Instance variables must be initialized by the time the the object is constructed and if they are final you won't be able to reassign values to them. If it's an instance variable then each instance of the class will have it's own copy, otherwise if it's static then there will be only one copy which will belong to the class itself.

When will I use a Class Variable in Java v.s an Instance Variable?

Here is a generic class that I have defined, what I would like to know is when I am creating more specific classes for instance a CAR class when would I use a Class Variable? My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
An instance variable allows each instance of a class / object that has been created from the class to have a separate copy of the instance variable per object?
So an instance variable is useful for defining the properties of a class / data-type e.g a House would have a location, but now when would I use a class variable in a House object? or in other words what is the correct use of a class object in designing a class?
public class InstanceVaribale {
public int id; //Instance Variable: each object of this class will have a seperate copy of this variable that will exist during the life cycle of the object.
static int count = 0; //Class Variable: each object of this class will contain a single copy of this variable which has the same value unless mutated during the lifecycle of the objects.
InstanceVaribale() {
count++;
}
public static void main(String[] args) {
InstanceVaribale A = new InstanceVaribale();
System.out.println(A.count);
InstanceVaribale B = new InstanceVaribale();
System.out.println(B.count);
System.out.println(A.id);
System.out.println(A.count);
System.out.println(B.id);
System.out.println(B.count);
InstanceVaribale C = new InstanceVaribale();
System.out.println(C.count);
}
}
My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
No. It's not that "each object will contain a single copy". A static variable is associated with the type rather than each instance of the type. The instances don't have the variable at all.
There's exactly one variable (assuming you're only loading it from one classloader) however many instances of the type there are. No instances? Still one variable. A million instances? Still one variable.
Static variables are mostly useful for constants or constant-alikes - things like loggers, or "the set of valid prices" etc. Things which don't change over the course of the application. They should almost always be final in my experience, and the type should be an immutable type (like String). Where possible, use immutable collections too for static variables - or make sure the variable is private and that you never mutate the collection within the class.
You should avoid using static variables to store global changing state. It makes code much harder to test and reason about.
Static variables are used to store values that are shared between all instances of the class.
If this is not the case, it should be an instance variable.
1. Every object of the class will have its own copy of Instance Variable,its One per Object.
2. But static variable will be shared by all the objects of the class, its One per Class.
3. Now i will give 2 example where these two will have importance.
Instance variable:
Consider a Gaming Program, then each player will have different Name, Scores, Weapons-power, Stage reached, etc.....
Static variable:
Consider a Banking program, where each client will be given an Id, which is greater and unique than the previous one, so static variable will be apt for this.

Categories

Resources