I think to a common Singleton Design Pattern:
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
}
as far as I know, costructors are NON static methods because they can use the context reference "this" (which is forbidden in static contexts). On the other hand, static members can access only static members.
So how is it possible that static member getInstance() is accessing the non static member constructor?
When you see an object creation like new Singleton() you must distinguish the new operator from the constructor code or to be more precise the initializer code.
The new operator is "like" a static method call. It doesn't need an instance of an object, because it creates one.
The constructor code is more "like" an instance method, except that it has no return type. But it can access the this reference.
At least you will see the difference when you dive into the generated bytecode. The new operator will lead to this bytecode instruction.
NEW yourpackage/Singleton
This instruction only creates the object in memory. See jvms-6.5.new
After the object is created it is initialized by executing the initializer code. In the bytecode it looks like:
INVOKESPECIAL yourpackage/Singleton.<init> ()V
The initializer code is more than only the constructor code. It invokes the super class's initializer and initializes instance fields.
Also see the java virtual machine specification 2.9
At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name . This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Instance initialization methods may be invoked only within the Java Virtual Machine by the invokespecial instruction (§invokespecial), and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (JLS §6.6) of the constructor from which it was derived
Constructors are not methods. Static methods are associated with a class, and non-static methods are associated with instances of that class. You cannot call non-static method from a static method because there is no instance associated with the static method. You can call constructors from static methods because constructors are associated with classes, not instances.
Constructors can use "this" reference only after the object is instantiated, i.e. after the constructor is called.
Related
I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.
This is a very wide-spread enum singleton code:
public enum enumClazz{
INSTANCE
enumClazz(){
//do something
}
}
and a bunch of places said it is a lazy initialization. But I am confused after I read Chapter 7 of 'Inside the Java Virtual Machine' -- The Lifetime of a Type:
The Java virtual machine specification gives implementations
flexibility in the timing of class and interface loading and linking,
but strictly defines the timing of initialization. All implementations
must initialize each class or interface on its first active use. The
following six situations qualify as active uses:
A new instance of a class is created (in bytecodes, the execution of a new instruction. Alternatively, via implicit creation,
reflection, cloning, or deserialization.)
The invocation of a static method declared by a class (in bytecodes, the execution of an invokestatic instruction)
The use or assignment of a static field declared by a class or interface, except for static fields that are final and initialized by
a compile-time constant expression (in bytecodes, the execution of a
getstatic or putstatic instruction)
The invocation of certain reflective methods in the Java API, such as methods in class Class or in classes in the java.lang.reflect
package
The initialization of a subclass of a class (Initialization of a class requires prior initialization of its superclass.)
The designation of a class as the initial class (with the main()< method) when a Java virtual machine starts up
The third point with bold style clarify that if the field is static final, the initialization of the field is happened at compile-time. Likewise, the INSTANCE in enumClazz is implicitly equal to public static final and comply with the third point.
Can someone correct me if my understanding is wrong?
enum instance fields are not "initialized by a compile-time constant expression". They
can't be, because only String and primitive types are possible types for a compile-time constant expression.
That means that the class will be initialized when INSTANCE is first accessed (which is exactly the desired effect).
The exception in the bold text above exists, because those constants (static final fields initialized with a compile-time constant expression) will effectively be inlined during compilation:
class A {
public static final String FOO = "foo";
static {
System.out.println("initializing A");
}
}
class B {
public static void main(String[] args) {
System.out.println(A.FOO);
}
}
Executing class B in this example will not initialize A (and will not print "initializing A"). And if you look into the bytecode generated for B you'll see a string literal with the value "foo" and no reference to the class A.
The third point with bold style clarify that if the field is 'static final', the initialzation of the field is happened at complie-time
Not exactly - it only applies to "static fields that are final and initialized by a compile-time constant expression":
static final String = "abc"; //compile time constant
static final Object = new Object(); //initialised at runtime
In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code.
So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.
Can anyone please explain me why it is illegal for static method to invoke a non static method?
A non-static method is an instance method which acts upon a specific instance (object), and has access to that object's members. A static method is not associated with a specific instance.
It is legal to call a non-static method if you provide an instance:
class Foo
{
public static void f()
{
instanceMethod(); // Not OK - no instance provided.
this.instanceMethod(); // Not OK - no "this" in static methods.
new Foo().instanceMethod(); // OK because you provide an instance
}
public void instanceMethod() {}
}
because to call static method you don't need object of class, where to call non static method you need,
Static method is associated with class where non static method is associated with state (Object)
A non-static method is a method that executes in the context of an instance . Without an instance it makes no sense to call one, so the compiler prevents you from doing so - ie it's illegal.
If a method doesn't access any instance fields (aka instance variables) then it should probably be changed to be a static method.
non static methods have the implicit parameter this which static methods have not (because there is no this)
Alone because of this fact it would not be possible to call non-static methods form static ones.
Static methods belong to the class. Non static methods belong to an instance.
The non static method require an instance (this) to be executed on. The static method don't require any instance, since the class itself is the instance to which it belongs.
If I have 100 object instance, every nonStatic() method invocation affects the state of a different object. So every nonStatic method is 'different' because it acts on different entities.
At the same time, even if I have 100 instance of an object, calling staticMethod() doesn't affect any of those instances, because it can only affect the static members of the class.
There is 1 class and 1 instance of every static methods or static member variables.
For the non static members we have every single method associated to the class instance.
So if you would be able to call the nonStatic method, from a static method, which of the 100 instance would be affected? You see: it doesn't make sense.
Static methods are connected with the class.
Regular methods are connected to the object.
In static method there is no object on which you can run the non-static method.
It is not illegal to call a non-static method from a static method. Whenever you invoke a static method there is no need of an instance of a class whereas in case of non-static case you do.
I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.
I have a simple question here.
If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(
usually I declare it like this :
private int number;
)
can it be used in a different object which was also made [declared] in the main class?
btw I do not care about security atm, I just want to make something work, don't care about protection)
Here's a telling quote from Java Language Specification:
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[Example program follows...]
In short, a static field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static field as a variable shared by instances of the class, but it's much more consistent to think of static fields as belonging to the class, just like static method also belongs to the class, etc.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static members through an instance instead of a type expression.
Related questions
Java - static methods best practices
Static methods
calling non-static method in static method in Java
non-static variable cannot be referenced from a static context (java)
When NOT to use the static keyword in Java?
Static variables and methods
If the class holding 'number' is called MyClass
you can refer to it as MyClass.number from any method.
Doing so for a variable is not good design though.
There are really two issues here: public vs. private in the context of inner classes, and static variables.
Part 1:
static means that you don't need an instance of the class to access that variable. Suppose you have some code like:
class MyClass {
public static String message = "Hello, World!";
}
You can access the property this way:
System.out.println(MyClass.message);
If you remove the static keyword, you would instead do:
System.out.println(new MyClass().message);
You are accessing the property in the context of an instance, which is a copy of the class created by the new keyword.
Part 2:
If you define two classes in the same java file, one of them must be an inner class. An inner class can have a static keyword, just like a property. If static, it can be used separately. If not-static, it can only be used in the context of a class instance.
Ex:
class MyClass {
public static class InnerClass {
}
}
Then you can do:
new MyClass.InnerClass();
Without the 'static', you would need:
new MyClass().new InnerClass(); //I think
If an inner class is static, it can only access static properties from the outer class. If the inner class is non-static, it can access any property. An inner class doesn't respect the rules of public, protected, or private. So the following is legal:
class MyClass {
private String message;
private class InnerClass {
public InnerClass() {
System.out.println(message);
}
}
}
If the inner class has keyword static, this would not work, since message is not static.
static variables are shared by all instances of a given class. If it's public, it is visible to everything.
non-static variables belong to only one instance.
Since your main method is static, it can only see static variables. But you should avoid working statically - make an instance of a class, and pass the data around as method/constructor parameters, rather than sharing it via static variables.