Why non-static variables/methods are not accessible inside a static method? - static

Need the reason from JVM side. Explanation of the flow of the JVM is much appreciated(In simply words).

Static variables and methods do not belong to an object, but they exist on an outermost level.
Conversely, non-static variables and methods belong to an instantiated object.
This means that non-static variables and methods are not accessible to static methods because static methods would not have an object on which to operate.
Let me do an example:
Imagine the class Foo is defined as
public class Foo{
public static int a;
}
We can do operations like
public static int main(String[] args){
Foo.a = 10;
int b = Foo.a - 5;
}
without instantiating an object
Foo foo = new Foo();
Now think about the following class
public class Bar{
int a = 10;
public static void doSomething(){
this.a = 5;
}
}
We know the keyword this refers to the object in use, but doSomething() it is not linked to an object, so what object does this refer to?
This is why we can't access non-static variables and methods inside a static method.

So to understand this you first need no understand what a static method is. Basically, a static method is a method inside a class that can be called even when the class hasn't been initiated.
These static methods (or variables) exist independently of any initiation of the class.
In general anything static should be avoided as they are kinda an antipattern when it comes to javas object-oriented approach to things.

Related

Is it bad to wrap singleton instance methods in static methods?

Is there a con to implementing a singleton that wraps instance methods with static ones?
For example:
public void DoStuff() { instance._DoStuff(); }
private void _DoStuff() {
...
}
And of course instance would be static. But it would be nicer to call:
Singleton.DoStuff();
Instead of:
Singleton.GetInstance().DoStuff();
I think it depends.
First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.
Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.
So you really have this difference:
var instance = Singleton.GetInstance();
...
instance.DoStuff ()
Vs
Singleton.DoStuff ()
This means that you can pass a singleton object around and not have to know static calls.
Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

Running an object's method from within a static method

I have two classes: Board, Player. The Board class uses static methods to calculate what happens when a player lands on a certain space on the board.
I pass the player object, p1, into the Board class. One of the static methods in the Board class needs to access methods in the p1 object. I have a basic understanding that static methods belong to the class and not the instance, but is there a way to access p1's methods without making p1 static?
Offcourse you can invoke INSTANCE method of Player since you have REFERENCE TO PLAYER OBJECT
class Board{
public static void land(Player p1){
p1.performAction();
}
}
What you cannot do, is invoke an INSTANCE METHOD OF BOARD class, since the static method in board class is not executed in the context of an instance.
Thus, compiler will spit out error if you try to do this -
class Board{
public static void land(){
performAction();
}
private void performAction(){
//instance method
}
}
However, you can invoke an instance method from another instance method, below would work - since while invoking doAction() from performAction() you are already in the context of an instance
class Board{
private void performAction(){
doAction();
}
private void doAction(){
}
}

What does static refer to being "stuck" to?

I'm trying to give myself a mapped idea of the word static (using my current noun definition of static, not having a good understanding of the adjective definition), but it would seem that non-static variables and methods actually are "stuck" (or better said referencing/referring) to objects/instances. So what is the terminology static actually describing about the declared methods/variables?
The words "static" and "dynamic" are frequently used as opposites in programming terminology.
Something that is dynamic is something that changes; in the context of a class, it is something that takes on different values or behaviors with each instance (object).
Something that is static does not change; it is in stasis. So a static variable of a class does not take on different values with each instance.
Static electricity doesn't move; it is stuck in one place, on your socks. Dynamic electricity, in motion in a wire, can do much more powerful things.
I think this question here provides a very detailed answer: What is "static"?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.

Static and Normal class combined in one class

I am trying my best to explain the situation. I hope, what I wrote, is understandable.
We already have class defined like
public ref class TestClass
{
public:
TestClass();
virtual ~TestClass();
protected:
Car* m_car;
}
TestClass is managed C++ and Car is unmanaged C++.
So far so good, but now I need to make static object of TestClass also. So I modify the code like below
public ref class TestClass
{
private:
static TestClass^ s_test = nullptr ;
public:
TestClass();
virtual ~TestClass();
static TestClass^ Instance();
protected:
Car* m_car;
}
When I want to use static instant of the class, I just get it from calling
TestClass staticobj = TestClass::Instance();
Elsewhere, just call
TestClass normalobj = gcnew TestClass();
Instance function is creating s_test static object and returns it.
TestClass ^ TestClass::Instance()
{
if(s_test == nullptr)
{
s_test = gcnew TestClass();
s_test->m_car = new Car();
}
return s_test;
}
Is it a good approach?
Is there any other better approach to accomplish same thing?
Edit :
FYI Above code works.
I combined Krizz and Reed Copsey’s solutions. That solve independent Singleton and memory leak.
Here is my sample code,
Special Singleton class derived from test class,
public ref class SpecialSingletonTestClass: public TestClass
{
private:
static SpecialSingletonTestClass ^ s_ SpecialSingletonTestClass = nullptr;
public:
SpecialSingletonTestClass ();
static SpecialSingletonTestClass ^ Instance();
};
Changed the testclass so it has now one more finalizer function.
public ref class TestClass
{
public:
TestClass ();
virtual ~ TestClass ();
! TestClass ();
protected:
Car* m_car;
}
I tested above pattern , it worked.
Thanks you guys,
L.E.
Is it a good approach?
I would probably not consider this a good approach, as you're making a single class both a singleton and a normal class that you can instance directly.
Typically, if you need a singleton, this would preclude the need or desire to be able to instantiate the class.
If you truly need to have a way to have a "global" instance of this class, I would encapsulate that in a separate class which implements the singleton. This would, at least, make it clear that you are dealing with something that's a single instance in that case. I would not mix both use cases into a single class.
Well, actually there is an issue with memory leaks in your code.
You declare only virtual ~TestClass(); which, for managed classes, are internally turned by C++/CLI compiler into implementation of IDisposable.Dispose().
Therefore, if you put delete car into it, it will be called only if you delete test_class or, e.g. wrap into using (TestClass tst) {} block when using from C#.
It will not be called when object is GCed!
To be sure it is called you need to add finalizer to your class !MyClass(); which is turned by compiler into virtual void Finalize() and thus non-deterministically called when GC is freeing an object.
And it is the only way to free m_car of singleton object.
Therefore, I suggest:
TestClass()
{
m_car = new Car();
}
~TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
!TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
I'm unsure as to what situation you could possibly be in that would require both singleton-style semantics and normal creation semantics for the same class.
As far as what you've coded though, it looks completely fine. My only comments would be that your Instance() function shouldn't need to perform construction on Car, the Instance() function should just call the default constructor of TestClass which should do all that.
EDIT
In reference to:
#crush . The class is already define i just need to get static object of it. Singleton means only one object of the class, but in this case, class have multiple normal object. But i want to use only one object of this class for one specific goal only for limited period of time. – L.E. 2 mins ago
A singleton is (usually) a sign of bad design - alot of people call it an anti-pattern actually. Chances are if you just need this one single specific instance of this class for a limited period of time there are some issues:
Singleton design is made for static-style existence - the variable will live for the scope of your program after lazily initialized.
Allowing global access will move your code towards spaghetti logic. You'd be better off dynamically allocating the one you need and passing the pointer to it to where you need it to be. A shared_ptr would be good for this.
You should find a way around the singleton-style implementation in this case even if it's more work for you - it'll almost certainly be better design.

In php we can access static member functions using class objects. Can someone please tell any practicle use of this feature

In php we can call static member functions using class objects. For example
class Human
{
public static function Speak()
{
echo "I am a human.";
}
}
$human = new Human();
$human->Speak();
What we would expect is that a static member function can only be called using the class name and not the class instance variable (object). But what i have seen while programming is that php allows calling a static member function using the class object also. Is there any practical use or some important reason that this feature has been provided in php ?
This feature exists in java and c++ also. Thanks Oli for pointing this out in your response.
This is the same as in other OO languages, such as C++ and Java. Why would you want the interpreter to prevent this?
UPDATE
My best guess for this (and this is only a guess) is "for convenience". In essence, why should the user of your class necessarily care whether a given member function is static or not? In some circumstances, this will certainly matter; in others, maybe not. I'm not saying this is a great justification, but it's all I can come up with!
it allows you to abstract from the particular definition of the method, so that for example if you had to turn it into a static one at some point, you don't have to rewrite all the method calls!
I can't answer for PHP, (or really for anything) but consider this hypothetical C++:
class base{
public:
static void speak(){cout<<"base\n";}
};
class sub :public base {
public:
static void speak(){cout<<"sub\n"; }
};
int _tmain(int argc, _TCHAR* argv[]){
base *base1 = new base();
base1->speak();
sub *sub1 = new sub();
sub1->speak();
base *sub2 = new sub();
sub2->speak();
((sub*)sub2)->speak();
}
The output would be:
base
sub
base
sub
I'm sure it could be useful... maybe helping you determine which class's static method you should call based on the object currently in hand.

Resources