Home > Net >  Differents in static methods and non static methods in classes without fields
Differents in static methods and non static methods in classes without fields

Time:12-14

Someone once wrote:

The space required for an instance depends only on the fields.

The methods require memory too but only one time per class. Like static fields. That memory is allocated when the class is loaded.

But what happens if a class with say like 5 methods and no fields get multiple instances in fields of other classes(composition). Do they require more memory? Or would it be the same as static methods?

I do ask this question also because maybe it even gets optimised when compiling?

Is there a differents to static class with static methods? Other than u need to create the class each time or pass it around?

Example:

class Test1
{
    public void DoThis()
    {
        ...
    }

    public void DoThat()
    {
        ...
    }
}

class Test2
{
    public void DoSomething()
    {
        ...
    }

    private Test1 sample = new Test1();

}

class Test3
{
    public void DoSomethingElse()
    {
        ...
    }

    private Test1 sample = new Test1();

}

And so on...

CodePudding user response:

"Behind the scenes", a class method is just like a static method, with the class instance beeing passes by reference as the first parameter.

That is, unless you use virtual methds, which "behind the scenes" are saved as instance members.

That is, because as long as you don't override a method, there is simply no reason to waste an instance's space.

Therefore, the size of both your class instances won't be affected by any non-virtual method you add to the class.

This concept can change between programming languages tho. For example, in Java and Python class methods are virtual by default.

  • Related