What is the reason why a static method of a particular class cannot refer the same instance of the class(object) AND an instance of another class(object)?
I read this in a textbook.
What is the reason why a static method of a particular class cannot refer the same instance of the class(object) AND an instance of another class(object)?
I read this in a textbook.
Because static
can be used without any instance of the class. For example, when you use Integer.parseInt(...)
, you are calling it using the name of the class Integer
, you never created an instance.
System.out.println(Integer.parseInt("123")); // Called with the name of the class
So, what if you could refer an instance inside that static
method? If the user calls it with the name of the class (without creating any instance) the method won't have any instance to refer to.
Note that you can also call a static
method with an instance, but the recommended way is to call it with the name of the class, to emphasize that it's an static
method:
Integer i = 0;
System.out.println(i.parseInt("123")); // Can also be called with an instance, but not recommended
To which instance would the static method (which is not associated with any instance) be referring?
Answer: none/undecidable; it doesn't make any sense as there can be 0..n instances.
Instance methods can only be accessed when you create the object of that particular class.Static methods can only access the instance methods if you create an instance of the particular class.