-7

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.

user3243076
  • 1
  • 1
  • 1
  • Because static methods aren't bound to an object instance. How would Java know what object to use? Static methods can be called without having created any instances. – kenm Jan 28 '14 at 04:56
  • Static methods can be called without instantiation of an object of that class. They can refer to an instance method if an object instance of passed to the static method. – Pat Mustard Jan 28 '14 at 04:56

3 Answers3

1

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
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
0

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.

Ajay
  • 643
  • 2
  • 10
  • 27