Java convention on reference to methods and variables - java

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

Related

What's the benefit of using class name to access static methods and static variables in java instead of creating objects and calling them? [duplicate]

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
Example:
Obj x = new Obj();
x.someMethod();
...or:
Obj.someMethod(); // Is this the static way?
I'm rather confused!
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method:
double convertMpgToKpl(double mpg)
...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):
void setMileage(double mpg)
...can't be static since it's inconceivable to call the method before any Car has been constructed.
(By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:
Car theMoreEfficientOf(Car c1, Car c2)
Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.
Define static methods in the following scenarios only:
If you are writing utility classes and they are not supposed to be changed.
If the method is not using any instance variable.
If any operation is not dependent on instance creation.
If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
There are some valid reasons to use static methods:
Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?
Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.
Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.
Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).
You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.
Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.
After reading Misko's articles I believe that static methods are bad from a testing point of view. You should have factories instead(maybe using a dependency injection tool like Guice).
how do I ensure that I only have one of something
only have one of something
The problem of “how do I ensure that I
only have one of something” is nicely
sidestepped. You instantiate only a
single ApplicationFactory in your
main, and as a result, you only
instantiate a single instance of all
of your singletons.
The basic issue with static methods is they are procedural code
The basic issue with static methods is
they are procedural code. I have no
idea how to unit-test procedural code.
Unit-testing assumes that I can
instantiate a piece of my application
in isolation. During the instantiation
I wire the dependencies with
mocks/friendlies which replace the
real dependencies. With procedural
programing there is nothing to "wire"
since there are no objects, the code
and data are separate.
A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.
Consider the following example:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
If you want to use non-static fields of a class, you must use a non-static method.
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111 Indian BBDIT
222 American BBDIT
333 China BBDIT
Static methods are not associated with an instance, so they can not access any non-static fields in the class.
You would use a static method if the method does not use any fields (or only static fields) of a class.
If any non-static fields of a class are used you must use a non-static method.
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
Use a static method when you want to be able to access the method without an instance of the class.
Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.
Static:
Obj.someMethod
Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
Static methods can be used if
One does not want to perform an action on an instance (utility methods)
As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below
1. new ABCClass(double farenheit).convertFarenheitToCelcium()
2. ABCClass.convertFarenheitToCelcium(double farenheit)
the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:
Math.random()
Math.sqrt(double)
Math.min(int, int)
StringUtils.isEmpty(String)
StringUtils.isBlank(String)
One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.
NOTE:
Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:
new MockUp<ClassName>() {
#Mock
public int doSomething(Input input1, Input input2){
return returnValue;
}
};
I found a nice description, when to use static methods:
There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :
If a method doesn't modify state of object, or not using any instance variables.
You want to call method without creating instance of that class.
A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.
Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.
If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.
Source is here
Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.
We use static method when we no need to be invoked method using instance.
A static method has two main purposes:
For utility or helper methods that don't require any object state.
Since there is no need to access instance variables, having static
methods eliminates the need for the caller to instantiate the object
just to call the method.
For the state that is shared by all
instances of the class, like a counter. All instance must share the
same state. Methods that merely use that state should be static as
well.
You should use static methods whenever,
The code in the method is not dependent on instance creation and is
not using any instance variable.
A particular piece of code is to be shared by all the instance methods.
The definition of the method should not be changed or overridden.
you are writing utility classes that should not be changed.
https://www.tutorialspoint.com/When-to-use-static-methods-in-Java
In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)
I am wondering when to use static methods?
A common use for static methods is to access static fields.
But you can have static methods, without referencing static variables. Helper methods without referring static variable can be found in some java classes like java.lang.Math
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.
Example:
public class Demo
{
public static void main(String... args)
{
Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:
Displ(); //By method name itself
Demo.Displ(); //By using class name//Recommended
d.Displ(); //By using instance //Not recommended
}
public static void Displ()
{
System.out.println("This static method needs to be called explicitly");
}
}
Output:-
This static method is executed by JVM
This static method needs to be called explicitly
This static method needs to be called explicitly
This static method needs to be called explicitly
The only reasonable place to use static methods are probably Math functions, and of course main() must be static, and maybe small factory-methods. But logic should not be kept in static methods.

Running a class method concurrently in multiple threads [duplicate]

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
Example:
Obj x = new Obj();
x.someMethod();
...or:
Obj.someMethod(); // Is this the static way?
I'm rather confused!
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method:
double convertMpgToKpl(double mpg)
...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):
void setMileage(double mpg)
...can't be static since it's inconceivable to call the method before any Car has been constructed.
(By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:
Car theMoreEfficientOf(Car c1, Car c2)
Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.
Define static methods in the following scenarios only:
If you are writing utility classes and they are not supposed to be changed.
If the method is not using any instance variable.
If any operation is not dependent on instance creation.
If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
There are some valid reasons to use static methods:
Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?
Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.
Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.
Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).
You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.
Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.
After reading Misko's articles I believe that static methods are bad from a testing point of view. You should have factories instead(maybe using a dependency injection tool like Guice).
how do I ensure that I only have one of something
only have one of something
The problem of “how do I ensure that I
only have one of something” is nicely
sidestepped. You instantiate only a
single ApplicationFactory in your
main, and as a result, you only
instantiate a single instance of all
of your singletons.
The basic issue with static methods is they are procedural code
The basic issue with static methods is
they are procedural code. I have no
idea how to unit-test procedural code.
Unit-testing assumes that I can
instantiate a piece of my application
in isolation. During the instantiation
I wire the dependencies with
mocks/friendlies which replace the
real dependencies. With procedural
programing there is nothing to "wire"
since there are no objects, the code
and data are separate.
A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.
Consider the following example:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
If you want to use non-static fields of a class, you must use a non-static method.
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111 Indian BBDIT
222 American BBDIT
333 China BBDIT
Static methods are not associated with an instance, so they can not access any non-static fields in the class.
You would use a static method if the method does not use any fields (or only static fields) of a class.
If any non-static fields of a class are used you must use a non-static method.
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
Use a static method when you want to be able to access the method without an instance of the class.
Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.
Static:
Obj.someMethod
Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
Static methods can be used if
One does not want to perform an action on an instance (utility methods)
As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below
1. new ABCClass(double farenheit).convertFarenheitToCelcium()
2. ABCClass.convertFarenheitToCelcium(double farenheit)
the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:
Math.random()
Math.sqrt(double)
Math.min(int, int)
StringUtils.isEmpty(String)
StringUtils.isBlank(String)
One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.
NOTE:
Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:
new MockUp<ClassName>() {
#Mock
public int doSomething(Input input1, Input input2){
return returnValue;
}
};
I found a nice description, when to use static methods:
There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :
If a method doesn't modify state of object, or not using any instance variables.
You want to call method without creating instance of that class.
A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.
Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.
If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.
Source is here
Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.
We use static method when we no need to be invoked method using instance.
A static method has two main purposes:
For utility or helper methods that don't require any object state.
Since there is no need to access instance variables, having static
methods eliminates the need for the caller to instantiate the object
just to call the method.
For the state that is shared by all
instances of the class, like a counter. All instance must share the
same state. Methods that merely use that state should be static as
well.
You should use static methods whenever,
The code in the method is not dependent on instance creation and is
not using any instance variable.
A particular piece of code is to be shared by all the instance methods.
The definition of the method should not be changed or overridden.
you are writing utility classes that should not be changed.
https://www.tutorialspoint.com/When-to-use-static-methods-in-Java
In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)
I am wondering when to use static methods?
A common use for static methods is to access static fields.
But you can have static methods, without referencing static variables. Helper methods without referring static variable can be found in some java classes like java.lang.Math
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.
Example:
public class Demo
{
public static void main(String... args)
{
Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:
Displ(); //By method name itself
Demo.Displ(); //By using class name//Recommended
d.Displ(); //By using instance //Not recommended
}
public static void Displ()
{
System.out.println("This static method needs to be called explicitly");
}
}
Output:-
This static method is executed by JVM
This static method needs to be called explicitly
This static method needs to be called explicitly
This static method needs to be called explicitly
The only reasonable place to use static methods are probably Math functions, and of course main() must be static, and maybe small factory-methods. But logic should not be kept in static methods.

How Class/Static Methods get invoked

While reading The Ruby Programming Language I came to know that, class methods are invoked on an object which got the same name as class.
I found objective-c also does a similar thing from a blog. Here Classes happens to be instances of meta-classes.
As another major Object Oriented language i would love to know how Java implements/achieve this.
Edit
I appreciate the answers from everyone. But my question wasn't about how to invoke a class method. As many answers were answering that. Apologies if my question was not well framed or it gave you a wrong idea.
In Java We can call static methods with class name.like
ClassName.staticMethod(args);
Keep in mind that they are class level methods and variables and beyond to any object , So thats why they are called by class name.
You can see its live demo by JVM when compiling any java program with error because main is also a static method
public class TradingSystem {
String description = "electronic trading system";
public static void main(String[] args) {
description = "commodity trading system";
}
}
Cannot make a static reference to the non-static field description
at TradingSystem.main(TradingSystem.java:8)
Also see 10 points about static keyword in Java AND Here is the doc
In the Java language, static methods are invoked on the class instead of an object e.g. System.currentTimeMillis. So conceptually this is very similar to Ruby, ObjC, Smalltalk, etc.
Unlike Ruby and Objective C, there is no object instance that those methods get invoked upon: The Java bytecode has a special bytecode instruction that invokes the static method; this bytecode instruction does not use an object pointer from the stack:
INVOKESTATIC "java/lang/System" "currentTimeMillis" "()J"
When using reflection, this special handling of static methods is represented by the fact that you don't need to specify an object that the method is called upon. Instead, you can supply null as the target of the call.
Refer the JLS:
A class method is always invoked without reference to a particular object.
When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time, static (early) binding.
Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as
ClassName.methodName(args)
moreover a static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.
Official Docs
In java static methods belongs to the class rather than objects of that class. So, static methods are called by className as:
ClassName.staticMethod();
static method or variables are invoked using the class itself.
e.g.
if you have a static member as public static Integer age in class Employee, then you invoke it using Employee.age
same goes with methods also. e.g. Employee.paySalary();
Let us consider an example.
public class StaticDemo {
public static void methodToPrintSomething(){
System.out.println("printing any crap");
}
public static void main(String[] args) {
StaticDemo.methodToPrintSomething();
StaticDemo obj = new StaticDemo();
obj .methodToPrintSomething();
}
}
Here method is called using obj.methodToPrintSomething(). Another interesting thing you can find is the statement obj.methodToPrintSomething(). We are creating an object to call a static method, but that does not mean we are calling methodToPrintSomething() on the object. As it is static, internally the statement obj.methodToPrintSomething() will be treated as StaticDemo.methodToPrintSomething()

Java and static member/function access without object

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

Difference between accessing static instance variables using the keyword this and Class name

I have got the following java class. When I am calling the login method in my constructor, I access the static instance variable username using the class name, and the static instance variable password using the keyword this. My question is what is the difference between the two approaches? Which one should be used in what situation?
public class MyClass {
private Main main;
private static String username = "mylogindetails";
private static String password = "mypassword";
public MyClass(){
this.main = new Main();
this.main.login(MyClass.username, this.password);
}
public static void main(String args[]){
MyClass myclass = new myclass();
}
}
They are both equivalent.
However, accessing static members using this is misleading and should be avoided at all costs.
No difference.
Some feel that a static field or method should be accessed through the Class name, rather than through this or an instance, to highlight that it is a static. Eclipse, for example, has a config setting to flag a warning about a static resource being accessed through an instance reference.
My preferences, in order:
within the class itself, I would just reference the field without a qualifier
use the Class name
use this or an instance only if you feel the static nature of the field/method may change and it is a design detail that it is static that the clients of the class should not depend on (in which case, I would think about making it an instance method anyway to ensure how it is accessed)
There is no difference in this case, and I think it's compiled to the same bytecode (GETSTATIC).
But MyClass.username is preferred, because it reflects the nature of the field.
From Java Tutorial: Understanding Instance and Class Members:
Class variables are referenced by the
class name itself, as in
Bicycle.numberOfBicycles
This makes it clear that they are
class variables.
Note: You can also refer to static fields with an object reference like
myBike.numberOfBicycles
but this is discouraged because it does not make it clear that they are
class variables.
All instances of your class share the same password; password belongs to the class, not each instance, that's what static means.
So although you can access it from any instance, such usage is discouraged as it suggests the password is instance specific.
Remember that static variables are shared across all instances of your MyClass so using this to refer to them is misleading. Really it's just a style difference but you should not get in the habit of referring to it with this.
Well, static variables are not instance variables. Therefore , static instance variable is not a valid term.
You don't need to use either.
Because you've got an inner class you can directly access the static variable without an explicit reference to the outer class or to this
If using static fields is confusing, you can make them all caps to distinguish them. Often this is reserved for final static fields acting as constants though.

Categories

Resources