I am brand new to Java from a little of C++ and I am wondering what happens when I call a static method or access a static field without having an instance of the class:
class Foo {
public final static Scanner _input = new Scanner(System.in);
}
class Bar {
public final static Scanner _input = new Scanner(System.in);
}
...
SomeCode[Foo._input.nextInt()];
I can't imagine a temp object is created, but have no idea.
Thanks
I am wondering what happens when I call a static method or access a static field without having an instance of the class
It just accesses the field... it's as simple as that. It doesn't create an instance of Foo - it wouldn't need to.
The field isn't associated with any instance of the type - it's associated with the type itself. That's what static means in Java, basically. You should try to ignore any of the meanings of static in C++ which are somewhat different, I'm afraid.
One thing to be aware of is effectively a problem in the design of Java - you can access static members via references, but it doesn't mean what you'd expect. For example:
Foo foo = null;
Scanner scanner = foo._input;
That looks like it will go bang with a NullPointerException - but it doesn't. That code is equivalent to:
Foo foo = null;
Scanner scanner = Foo._input;
It's worth avoiding the first form of code as far as possible. It can be really misleading, particularly when you're calling methods - it looks like the call relies on the instance (and can be polymorphic) but actually both of those are incorrect :(
I can't imagine a temp object is created,
Nope. You use the class object to call the method.
temp object is created???
static keyword to create fields and methods that belong to the class, rather than to an instance of the class.
Heavily recommending
static fields are associated with the class itself. Their resolution is done at compile time; initialization of static variables (and static initialization blocks) are run when the class is loaded by the JVM.
As to how to access such variables (or methods), you can either use the class name, as you do; but Java also allows you to do that using instance variables of the class. Including null ones!
All these three expressions allow to access a static variable named bar in class Foo (provided that bar is visible by the caller):
Foo.bar; // using the class name
new Foo().bar; // using an instance
((Foo) null).bar; // using a null instance
You have used both static and final keyword , Both have different meaning.
When you declare any variable using static keyword then its declared as a class variable ,Means its common to all instance of that class. access using class name no need to use instance .
E.g.
Class Bycicle
{
static String Type ='exercise';
String Owner;
}
If you create 10 instance of this class then 1o copy of owner will created , while type will remain only one common copy for all 10 object. One object change type value then it will effect to all other object.
if you are declaring static with final then it common to all and also not allowed to change once it declared and initialize at compile time.
Go here for more interesting details click here
Related
Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.
I have a class, which has some private static final fields (unsure if it is correct to call these constants), and one other instance variable set just private, which is direct copy of one of the private static final fields.
Every time the object is created from other classes, I want it to have the same variables, as they are assigned in the class, and without creating a constructor, Java allows me access all of the methods with the correct returns as I would expect.
Is it okay to not create a constructor in this case?
There are at least two answers to your question:
It's fine not to include a constructor in your class. The Java compiler will add a default zero-parameters constructor for you.
It sounds like you shouldn't be constructing instances of your class in the first place. :-)
You've said
Every time the object is created from other classes, I want it to have the same variables, as they are assigned in the class, and without creating a constructor, Java allows me access all of the methods with the correct returns as I would expect.
It sounds like you have roughly:
class TheClass {
public final SomeType variable = /*...*/;
// ...
}
...and you're doing this:
TheClass instance = new TheClass();
doSomethingWith(instance.variable);
There's no reason to create an instance there, just use the class name directly:
doSomethingWith(TheClass.variable);
Java is somewhat interesting in that it allows you to access static members via instance references (instance.variable), but the normal way to access them is through the class (TheClass.variable).
Also, if your static members aren't final, you can get some very confusing-seeming behavior:
TheClass a = new TheClass();
a.variable = 1;
TheClass b = new TheClass();
b.variable = 2;
System.out.println(a.variable); // 2?!?!?!
So in general, best to avoid accessing static members via instance references.
Alternately, make the class a singleton with instance (non-static) members instead.
I didn't understand this part:
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Can you give an example please ?
Static methods are methods that are called without a reference to an instance of that object. So instance variables cannot be called statically, as each instance will have its own values. So in a static method, you need a specific instance of an object in order to know which value of the instance variable you are trying to use.
The difference is how you access these variables:
class myClass {
public static int staticVar;
public int nonStaticVar;
//Constructor initialises both
}
Static approach:
int otherVariable = MyClass.staticVar;
As you can see, for the static variable you do not need to make an object to access it. Note that you can imagine a static variable to have the trait "once per class", which means, that you can not have 2 versions of staticVar.
Non Static (instance variable):
MyClass instanceOfMyClass = new myClass();
int otherVariable2 = instanceOfMyClass.nonStaticVar;
To have 2 versions of nonStaticVar you can simply make 2 objects and give this variable different values in the 2 objects. Note that in this case you have to make an object.
Section 10.2 of Java conventions recommends using class names instead of objects to use static variables or methods, i.e. MyClass.variable1 or MyClass.methodName1() instead of
MyClass Obj1 = new MyClass();
Obj1.variable1;
Obj1.methodName1();
There is no explanation of the rationale behind this, although I suspect this has something to do with memory use. It would be great if someone could explain this.
I guess you mean "for static methods and variables".
There is no difference regarding memory, except of course if you create the instance just for calling the method. Conventions aren't for memory efficiency but for coder efficiency, which is directly related with the readability of the code.
The rationale is that by reading
MyClass.methodName1()
you know it's a static method and that it can't use or change your Obj1 instance.
And if you write
obj1.variable1; // note the "o" instead of "O", please do follow conventions
then the reader has to read your source code to know if variable1 is static or not.
If you use object for static variable access then compiler will replace it with Class Name only.
So
MyClass Obj1 = new MyClass();
Obj1.variable1;
Obj1.methodName1();
It is same as
MyClass.variable1;
MyClass.methodName1();
Now Why to differentiate? Answer is - It is for better reading If someone see method being called on Class then he immediately come to know that it is static method. Also it prevents generation of one additional object to access the method.
This has to do with public static methods and variables. Since these methods/variables are associated with the respective class rather than an instance of the class, it is nice to use refer to these methods or variables as className.methodName() or className.variableName
"Understanding Instance and Class Members" would be a good starting point to learn about the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class
It is only because, public static method or public static variable is not associated with any object, but the class. Though the language designer has given the flexibility of invoking them on objects, reader of the code would be confused whether those are static variable/methods or instance methods/variables. So readability is the reason behind asking the developers to invoke them on classes.
You are allowed to access static members either by using the class name notation or by accessing using an object. It is not recommended to use the object notation since it can be very confusing.
public class TheClass {
public static final staticValue = 10;
public static void staticMethod() {
System.out.println("Hello from static method");
}
public static void main(String ... args) {
TheClass obj = null;
// This is valid
System.out.println(obj.staticValue);
// And this too
System.out.println(obj.staticMethod());
// And this is also valid
System.out.println(((TheClass)null).staticValue);
// And this too
System.out.println(((TheClass)null).staticMethod());
}
}
It is much clearer if the static methods and variables are called with the class name notation.
static variable belongs to the class and not to object(instance).
A static variable can be accessed directly by the class name and doesn’t need any object.
it saves space not having to have variables for the same data for each class.
Syntax : <class-name>.<variable-name>
public class AA{
static int a =10;
}
You can call
System.out.println(AA.a);
System.out.println(aObject.a);
There is no differen between two calling but maintain coding convention to keep more readbale
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.