Running an object's method from within a static method - static-methods

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(){
}
}

Related

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

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.

Static class in Android

I have a question, I confuss about when I must use class static.
I understand that I have use class static when I need some methods that going to use many times in the code, and that class doesn´t need to be declarate, but in a example in android I find that code.
Where they declare a static class and call it with an instance...
Why did they do that?
public View getView(int position, View view, ViewGroup viewGroup) {
//View holder pattern
**ViewHolder holder;**
if(view ==null){
LayoutInflater layoutInflater=LayoutInflater.from(this.context);
view=layoutInflater.inflate(R.layout.list_item,null);
**holder=new ViewHolder();**
holder.txtView =(TextView) view.findViewById(R.id.txtView);
view.setTag(holder);
}
return view;
}
**static class ViewHolder{
private TextView txtView;
}**
Thanks for your explanation..
The advantage of having a static nested class over an non static one is, that to create an instance of the static nested class you don’t need an instance of the outer class. If you only have a non static inner class you need an object of the outer one to be able to create an instance.
Note that only nested classes can be static.

Silverlight Unit Testing multiple initializations with same tests

I have an object with lots of properties that I would like to test. I have written a TestMethod for each property, but the problem is that many of the properties manipulate the others when they are set. What I need is to be able to set up my test object, manipulate one of the variables, run the tests, reset the object to its original state, then repeat the process. That way, I can avoid having so much redundancy.
I looked into using a Data Driven approach (which is a perfect solution to this problem), but that doesn't seem to be available with the Silverlight Test Framework, since I can't find a way to use the DataSource attribute. I thought about trying to see if I could get access to the DataSource through the traditional MSTest framework, but alas, I only have Visual Studio Express.
I've thought to try to look into creating a custom test harness to see if that could solve this problem, but I thought I'd ask around for suggestions first.
Maybe I should just suck it up and write up all of the different configurations as separate TestInitialize Methods and comment out the ones I don't need as I go.
Any help would be greatly appreciated.
Update/Clarification:
Here is an example of how the object to be tested works. Say you have a shape with a position coordinate and coordinates for each side. When you Update the coordinates of the position or one of the sides, all other coordinates must be updated as well.
This is the functionality that is under test. What I would like to do is be able to set up multiple initializations (through ClassInitialize or what have you) where I would set up the initial value of my object and a mock containing the expected test results, then alter one of the properties in question. Something like this (this is for illustration only, so please ignore any poor practices xD):
// class under test (mock has the same properties & constructor)
public class MySquare
{
public Vector2 XYPosition;
public int Width;
public int Height;
public float TopSidePosition;
public float RightSidePosition;
...
public MySquare(float x, float y, int width, int height)
{
// set up all properties
}
}
// test object container
public class Container
{
public static MySquare square;
public static MySquareMock squareMock;
}
// desired test class initializations (it would be nice to be able to run each of these
// as well as the TestMethods and then reset to the next TestSetupClass)
[TestClass]
public class TestSetupClass1
{
[ClassInitialize]
public void SetupTest()
{
// set up initial value and expected result
Container.square = new MySquare(0, 0, 5, 5);
Container.squareMock = new MySquareMock(1, 1, 5, 5);
Container.square.XYPosition = new Vector2(1, 1);
}
}
[TestClass]
public class TestSetupClass2
{
[ClassInitialize]
public void SetupTest()
{
// set up initial value and expected result
Container.square = new MySquare(0, 0, 5, 5);
Container.squareMock = new MySquareMock(1, 0, 5, 5);
Container.square.RightSidePosition = 6;
}
}
// test methods
[TestClass]
public class TestMethods
{
[TestMethod]
public void TestPosition()
{
Assert.AreEqual(Container.squareMock.XYPosition, Container.square.XYPosition);
}
[TestMethod]
public void TestTopSidePosition()
{
Assert.AreEqual(Container.squareMock.XYTopSidePosition, Container.square.TopSidePosition);
}
// test method for each property
}
I didn't find a completely automated way of achieving my original goal, but I did come up with something pretty easy.
First, I created a singleton TestManager class to handle nearly all of my test setup, so that I only need one line in my MainPage (the test page) class. Within the TestManager, I added a string variable that I assign a name of a TestSetup class too from the MainPage.
Then, I created another TestClass called TestSetupClass and gave two static fields:
private static Type childType;
private static TestSetupClass childInstance;
In its constructor, I compare the underlying type to the class name specified in the TestManager and set the childType and childInstance if they match:
Type thisType = GetType().UnderlyingSystemType;
if (thisType.Name.Equals(TestManager.Instance.SetupClassName))
{
childType = thisType;
childInstance = this;
}
Next, I added a virtual method to the TestSetupClass with an AssemblyInitialize attribute. All of my setup classes inherit from TestSetupClass and override this method. Within the method, I use the childType to get MethodInfo for the child's overridden implementation of the method and invoke it using the childInstance:
MethodInfo childSetup = childType.GetMethod("Setup");
childSetup.Invoke(childInstance, null);
And voila! When you want to run a specific setup before running all the tests, you just specify its class name in the MainPage using the TestManager.
I know there are a few more places where I could have made this better, but it works, so what can you do.

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.

C# setting form.visible = false inside a method?

hi i have this lines of code that i cant make it work
the goal is simple setting the form1 to visible = false
public static void DoActions(string Cmd){
if(Cmd == true)
{
MainForm.Visible = false;
}
}
but i keep on having this error
An object reference is required for
the non-static field, method, or
property
usually i set the called methond to static.. so the error will go away
but on this case how do i do it?
thanks for any help guys
'System.Windows.Forms.Control.Invoke(System.Delegate)'
This is happening because DoActions is a static method rather than an instance method, however MainForm is an instance field / property. The distinction is that instance methods operate on an instance of the class on which they are defined, wheras static methods do not.
This means that wheras instance methods are able to access properties, fields and methods of their containing class through the this keyword, for example:
// Instance field
Form1 MainForm;
void InstanceMethod()
{
Form1 frm = this.MainForm;
}
You cannot do the same thing from inside a static method (think about it, what instance would it operate on?). Note that C# will implicitly assume the use of the this keyword in places where it makes sense (so the above example could have been written as Form1 frm = MainForm).
See C# Static Methods for an alternative explanation of static vs instance methods (this is an important concept in object oriented programming that you should take the time to understand properly).
In your example you probably want to change DoActions to an instance method (by removing the static declaration):
public void DoActions(string Cmd)
{
if(Cmd == true)
{
this.MainForm.Visible = false;
}
}
This will allow it to access the instance MainForm field / property, however this may cause problems elsewhere in your code in places where you attempt to call DoActions from another static method without supplying an object instance.
Set form opacity and showintaskbar property in property window:
this.Opacity = 0;
this.ShowInTaskbar = false;
Your method is static - and so cannot access MainForm.
Make your method non-static if it is not required to be so.
public void DoActions(string Cmd)
{
if(Cmd == true)
{
MainForm.Visible = false;
}
}
If it is required, then create a static field in your class and ensure it is set before this method runs.

Resources