[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 345
  • Last Modified:

Must Classes Be Instantiated?

If I have a class which has only methods in it, do I still need to instantiate the class first before I can call one of the methods?

Is there a way to avoid this and still have other code in other files? (I come from the old fashioned old world of non-OOP programming and assembly language.)

What happens internally behind the scenes when I instantiate a class of this form? What happens if I instantiate more than one copy of a class which only contains code? Does it make separate copies of the code, or is it somehow smart to know it doesn't need to do that?

class MyProcs
{
    public DoStuff()
    {
       ...code...
    }
}

class program
{
    static void Main()
    {
        MyProcs x = new MyProcs()    // Do I have to do this just to run code?
        x.DoStuff()
    }

Open in new window

0
deleyd
Asked:
deleyd
  • 2
3 Solutions
 
Ross-CCommented:
public DoStuff()
    {
       ...code...
    }

would need to be Instantiated but

public static DoStuff()
    {
       ...code...
    }

would not.
0
 
Ross-CCommented:
0
 
Paul JacksonCommented:
if you declare a class as static you don't have to instantiate it. The code is shared between calls.
If you instantiate a class it creates a unique instance of the code, that is executed for that call.
Generally for common code class files you would declare the classes as static.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now