Java Static Method Calling - java

is Calling a static Java method ( a factory class method ) creates an object of that Class ?
I mean a static method returns a value let's say an Array's size ( array is variable of class )
I've checked the code but couldn't see that the Object of that class never instantiated before calling the static method. ?
public static boolean isFiveInstance() {
return _instances.size() == 5;
}
and _instances is class variable
private static ArrayList<LocalMediaPlayer> _instances;
and is being created and filled in the constructer.

No it does not. That is the point behind creating static methods. Static methods use no instance variables of any object of the class they are defined in either, so everything you refer to inside your static method must be static also.
That is why you call a static method like Class.StaticMethod() instead of:
new Class().StaticMethod();
the new will instantiate that class, thus creating a new instance of that object.

No, static invocations do not instantiated objects (because they do not require one).
The first time you refer to a class, including static method invocation, the class is loaded. by the classloader.
That's where the static initializer comes into play:
static {
// do something
}
this block is called whenever the class is initialized (once per classloader)

No, calling a static method does not create an instance of the class. That's where static methods differ from instance methods. They don't need an instance of the class they belong to to be instantiated to be run.

Related

Why is an object needed to refer to a class member inside of a static method? [duplicate]

This question already has answers here:
java non-static method getBalance cannot be referenced from a static context
(4 answers)
Closed 5 years ago.
Compare the way I print the value of the members of this class, in the static method (main) v/s a non-static method (the print method). In the static method, I need to use an object of this class, whereas, in the non-static method, I can refer to the class members directly.
I understand that the scope of static is class-wide, and is not tied to an object. Could someone elaborate a bit further on why I need to use an object in the static method, and it's not needed in a non-static method.
public class TreeDriver {
Tree tree;
TreeNode p;
public TreeDriver() {
tree = new Tree();
p =null;
}
public static void main(String[] args) {
TreeDriver obj = new TreeDriver();
obj.print(obj.tree.root, obj.p);
}
public void print(TreeNode nodeA, TreeNode nodeB)
{
System.out.print(nodeA.val + ", " + nodeB.val);
System.out.print(tree.root.val + ", " + p.val);
}
}
The print method isn't a static method, so it can only be called on an instance of the TreeDriver class (i.e. it can't be called from the class directly, like TreeDriver.print(...))
From your perspective, there's no way around this really, as you're accessing the instance variables p and tree in your method.
I would add that it'd probably make more sense if you split out your driver methods (e.g. main(String[] args) away from your data model (i.e. the instance variables and the print method).
Static methods do not need an object instance to be called.
In your above example, another class could call your main function like so.
TreeDriver.main(args);
Notice that TreeDriver is not an instantiated object. Contrast this with how a different class would need to call print.
TreeDrvier newTreeDrvier = new TreeDriver();
newTreeDriver.print(nodeA, nodeB);
You need an instance of the TreeDriver object. Members are defined for an instance of the class, not for the class itself, unless the member itself is static, which in that case would make it a class variable.
By definition, you don't need an instance to call a static method. There's really nothing more to say about "why" than just "that's the definition of a static method."
A non-static method is associated with a specific instance. As an analogy, if I tell you to start the car, you go start a specific car - you can't just grab the key and turn it in mid-air and expect it to "work."

Why does this method call return the same reference every time it’s called?

public class SomeClass {
private static final SomeClass INSTANCE = new SomeClass();
private SomeClass() {}
public static SomeClass getInstance() {return INSTANCE;}
public static void main(String[] args) {
System.out.println(getInstance());
}
}
Why does the getInstance method always return the same reference every time?
The reason is that the field INSTANCE is both static and final.
static means its scope is bound to the enclosing class, and not any single instance of that class. (Even though you're not creating any instances of it anyway.) In a running Java program, there's only one of each class, even though a class may have many instances.
final means that the value of this field cannot be changed after it's initialised.
Because it's static, there's only one "slot" for the object, and because it's final the contents of this slot will never change, which is why returning those contents will always return the same thing.
You're assigning a reference to a constant (INSTANCE), and your getInstance method returns that constant, so yes, it always returns the same reference.
The reason is because you have declared the instance
private static final SomeClass INSTANCE = new SomeClass();
as final and static , so the instance will be allocated a single memory and that also be constant, therefore it is using singleton pattern
Take a look at this stuff -
Implementation of Singleton Pattern Class in Java Introduction
Yes it will return the same reference always as long as the class is loaded. Its static final
INSTANTA is declared final, which means its value cannot be changed once it has been initialized. Hence, program guarantees that getInstanta returns same instance always.
You declared both method and constant static. This means it is a member of the class instead of an object created from that class. As the class only exists once it will always return the same object. Furthermore since your variable is final it can never be assigned to a new object.

What is the purpose of static keyword in this simple example? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.

Difference between Static and final?

I'm always confused between static and final keywords in java.
How are they different ?
The static keyword can be used in 4 scenarios
static variables
static methods
static blocks of code
static nested class
Let's look at static variables and static methods first.
Static variable
It is a variable which belongs to the class and not to object (instance).
Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.variable
Static method
It is a method which belongs to the class and not to the object (instance).
A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
A static method can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.methodName()
A static method cannot refer to this or super keywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is static since it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.
A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading
So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.
class C {
public static int n = 42;
}
Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.
final on the other hand indicates that a particular variable cannot change after it is initialized.
class C {
public final int n = 42;
}
Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.
Also, classes can be declared final which indicates that they cannot be extended:
final class C {}
class B extends C {} // error!
Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:
class C {
public final void foo() {}
}
class B extends C {
public void foo() {} // error!
}
static means there is only one copy of the variable in memory shared by all instances of the class.
The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.
final -
1)When we apply "final" keyword to a variable,the value of that variable remains constant.
(or)
Once we declare a variable as final.the value of that variable cannot be changed.
2)It is useful when a variable value does not change during the life time of a program
static -
1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class
Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
Declaring
static final String color = "Black";
will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.
public class Speaker {
static String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //will provide output as "Black"
Speaker.color = "white";
System.out.println(Speaker.color); //will provide output as "White"
}}
Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.
public class Speaker {
static final String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //should provide output as "Black"
Speaker.color = "white"; //Error because the value of color is fixed.
System.out.println(Speaker.color); //Code won't execute.
}}
You may copy/paste this code directly into your emulator and try.
Easy Difference,
Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.
Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again.
you can create object of class but that object will not have different x in them.
if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.
Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.
"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so
Class A has x =5, i can call and change it by A.x=6; "
Static and final have some big differences:
Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:
public class Test{
public final int first = 10;
public static int second = 20;
public Test(){
second = second + 1
first = first + 1;
}
}
The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.
Static is something that any object in a class can call, that inherently belongs to an object type.
A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.
Some example code:
class someClass
{
public static int count=0;
public final String mName;
someClass(String name)
{
mname=name;
count=count+1;
}
public static void main(String args[])
{
someClass obj1=new someClass("obj1");
System.out.println("count="+count+" name="+obj1.mName);
someClass obj2=new someClass("obj2");
System.out.println("count="+count+" name="+obj2.mName);
}
}
Wikipedia contains the complete list of java keywords.
I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.
static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.
final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.
Static variable values can get changed although one copy of the variable traverse through the application, whereas Final Variable values can be initialized once and cannot be changed throughout the application.

How are field variables initialized in Java?

I tried to run this program but this gives a runtime error(StackOverflowError). If in class Static I make reference object ob, static, then no error occurs. Can anyone please explain me why is this happening and please explain me how are field variables(whether static or non static and whether reference or non reference variables) initialized?
public class Static {
public Static ob = new Static();
private int a;
public void win(Static obj) {
//System.out.printf("ob.a = %d\n", ob.a);
obj.a = 15;
System.out.printf("ob.a = %d", ob.a);
}
}
public class StaticTest {
public static void main(String args[])
{
Static obj=new Static();
//Static obj1=new Static();
// obj.win(obj1.ob);
}
}
Each time you instantiate an object of Static class (very confusing name BTW) you create an object of Static and instantiate it, which create another object of Static and instantiate it and so on... (so you get a StackOverflow error):
public Static ob = new Static();
Your code creates an instance of Static class.
When the instance is create their attributes are initialized. What your code does is to initialize the 'ob' attribute with pointing to a new Static instance.
Then the new instance of Static class is created, and ... you have an "infinite initialization loop".
If you attach 'static' keyworkd to an attribute you are creating a "class attribute", that is, an attributed shared among all instances of that class.
This means when you execute code and the first instance of Static is goind to be created JAva initialize the ob attribute. Subsequent instances of Static doesn't initialize it because it is shared among all.
See this sample: http://www.roseindia.net/java/beginners/staticvariable.shtml
static fields are initialized once for all instances of the class. This is why changing the type to static stops it from infinite recursion.
When the field is not static you create an infinite recursion which leads to a stack overflow; when you instantiate the object, it instantiates another, which instantiates another, and so on.
Static is at the class level and hence it is initialized when the class is loaded in the memory for the first time. Also static blocks are init in order of there declaration.
As against, the class variables (non static) are per object and are init when the object of that class is created, not in any specific order, I believe.
In your case, if you don't make ob static, it will try to init the Static class object and when try to inti the ob, it again go and create another Static (as it calls new Static()) and this goes on for ever until you run out of stack (StackoverFlow).
if you make ob static, this is init only once (when Static class is loaded in memory) and you are good to go.
If you create an instance level of a field, you are causing never-ending recursion, which ultimately ends up to StackOverFlow memory error.
If on the other hand you define your field as static you are avoiding the recursion, since the static field variables belong to the Class, not to the object instance. Classes in the JVM are only created once as opposed to Object instances, which can be numerous.

Categories

Resources