CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Aug 2009
    Posts
    12

    Static, Classes and Objects

    Hello, I'm a fairly new coder to C# (I have a little experience in C++ and Java but I never got farther than arrays) and I found that this language is fairly simple compare to it's complex older brother C++. With that being said, I picked up learning how to code which brings me here. Both C# and C++ are OOP, but I never got far enough in C++ to actually start handling objects, which brings me to C#. I've finally gotten to that point, and I need help trying to determine what Static, Classes and Objects are.

    tl;dr: In laymen's terms, define static, classes and objects. If you can, compare them to something someone who doesn't code would understand just to ease the transition.
    ---------

    I have done some research, so I'm not coming to you without doing my fair share of searching, so I'll relay what I believe I know.
    ---------

    Static is basically a defining keyterm. It makes a class/method non-changing meaning it can't be multiplied (what does this mean?). It also means that the class/method and anything inside it can't be accessed by something on the outside unless it's called directly via "class.whatever" (am I correct?). A class is basically a mold of an object. The class holds information that cannot be accessed unless it's an object.

    This is where I'm completely lost. I have no idea what's going on here. I came from C++ where there were no classes (or I haven't gotten to at least) and there were just methods. Someone care to correct what I know or properly define these terms? Many thanks.

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Static, Classes and Objects

    C++ does permit classes: http://www.cplusplus.com/doc/tutorial/classes/

    Since I can't say it better, I quote the linked article:

    A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.

    An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
    Instances are created by using the new keyword.

    If something is static, it means it belongs to the class, rather than belonging to a specific instance of a class.

    For example, suppose we had the following class:

    Code:
    class Student
    {
        //These are instance (non-static) variables; they belong
        // to a specific instance (object) of the student class
        string name;
        double gpa;
        
        //This is an instance (non-static) method.  It depends on 
        // instace variables
        public double getGPA() { return this.gpa };
    
        //This is a static method; notice how it does not depend on (or change) any 
        // instance variables.  The method belongs to the Student class, rather than
        // any particular student being represented by an instance of the class.
        public static int calculateGPA(int numberOfAs, int numberOfBs)
        {
            return (numberOfAs * 4 + numberOfBs*3) / (numberOfAs + numberOfBs);
        }
    }
    Obviously this is contrived example, but hopefully is illustrative.

    Does that make sense?
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    Aug 2009
    Posts
    12

    Re: Static, Classes and Objects

    So a class is just something that holds the data while the object IS the actual data within the class? In order to access the data within the class you have to create an object with the keyterm new?

  4. #4
    Join Date
    Dec 2008
    Posts
    144

    Re: Static, Classes and Objects

    The class is a blueprint. The object is the implementation of that blueprint.

    A static class and its contained static methods is different because you don't have to instantiate the class to use it. Instead of:
    Code:
    MyClass myClass = new MyClass()
    myClass.DoStuff(variable)
    you can directly call the method like this:
    Code:
    MyClass.DoStuff(variable)
    Code:
    if (Issue.Resolved)
    {
         ThreadTools.Click();
         MarkThreadResolved();
    }

  5. #5
    Join Date
    Aug 2009
    Posts
    12

    Re: Static, Classes and Objects

    So if that's the case, what are the uses of objects? It seems like all it does is shorten the call name.

    I mean, I could see your point if you wanted to make multiple copies of a class and then make everything in that class an instance. But I couldn't see myself using those objects down the line.

  6. #6
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Static, Classes and Objects

    I always get talkative with questions like this one.
    Structurally, classes are, as explained by others, just a way to group together some data, and methods closely related to that data. But beyond that, being a language tool, they provide you with a way to model various concepts (say, a window, or a button, or a bank account, or a web page, or an order, or a tree structure, or a video game enemy, or 3D vector, or a polygonal shape, or whatever...)

    The idea is that, in your class declaration, you specify what kind of data this concept is represented by, and what kind of operations it should be able to support (e.g. an Animal class has some internal data, and it can do things like Run(), MakeSound(), Eat(), and Sleep()).
    In that sense, classes are blueprints - outlining these concepts. We sometimes like to say that they are models of those concepts (rather than they represent the concepts themselves), because, when making a class, you only focus on those characteristics that matter for your application (or for a certain type of applications that might benefit from using it) - the Animal class from the previous example will not account for every conceivable property and ability of an animal; the goal is not to create an accurate digital copy. The goal is to create a representation of the given concept that is suitable to be used for solving problems in a given problem domain.

    However, a class is an abstraction of sorts: that's why your code normally can't work with classes, but with their instances (a.k.a. objects).
    If the idea of "instances" is confusing to you - don't worry, there's really nothing to it. A simple example: the concept and the words "human being" represents any human being, with all the characteristics and capabilities common to all human beings. Individual humans are instances of the "human being" - individuals like me, you, CreganTur, BioPhysEngr, that guy on TV, etc... We all have what all human beings have: head, eyes, arms, hair... But one person has brown hair, another has blond, someone has blue eyes, someone has green...
    Similarly, a class defines what kind of data it's objects can hold, but not the actual values - each instance has it's own set of values that are characteristic for the current state of that instance. The associated operations, we call then class methods, operate on objects, not classes, and are invoked on objects.
    Behind all this is the idea that classes enable you to define new, custom data types.
    Say you need a type to represent a car in your program. The language doesn't come with a convenient type predefined. Instead of scattering a bunch of variables around, pulling your hair trying to keep track of them, and messing with a bunch of free functions - you define a new type, by defining a class named Car (the name's up to you). Now you have your data structured, and the related methods are tied closely together.
    So you can do something as simple as this.
    Car car1 = new Car(); // creates new instance, and assigns it to a variable
    Car car2 = new Car(); // creates new, but different instance, and assigns it to a variable
    car1.Beep(); // beep once
    car2.Beep(2); // beep-beep

    Assuming these car objects internally hold a significant amount of data that defines their state (model, license plate #, current speed, max speed, beep sound, etc...), you can see how this is much more elegant and simple than having a bunch of variables lying around unstructured, and maintaining a separate set of them for each car instance you need in your app.

    If you've done any C# coding, you've probably been using objects and classes all along, without even realizing it. Almost everything in C# is a class instance.
    Even in your C++ explorations, there were classes and objects, you just didn't recognize them as such. Remeber cout, and cin? Those are objects of the ostream and istream classes defined in the standard library.

    You also might wanna read my answer to another question - there's a section I named A Crash Course in Classes.

    I'll follow up with a few lines about static shortly.
    Last edited by TheGreatCthulhu; March 16th, 2012 at 03:45 PM. Reason: spelling...

  7. #7
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Static, Classes and Objects

    Quote Originally Posted by Deathscreton View Post
    So if that's the case, what are the uses of objects? It seems like all it does is shorten the call name.

    I mean, I could see your point if you wanted to make multiple copies of a class and then make everything in that class an instance. But I couldn't see myself using those objects down the line.
    Hopefully, after reading what I wrote above, things are more clear. However, I feel I should answer this nevertheless. Often you will have more than one instance. For example, take the String class (which is what the string keyword really refers to in C#): the class itself defines what kind of data it can hold, and what you can do with it (split, change caps, insert strings...). The instances of the String class define the actual strings, and in an application, you will usually have a lot of strings. Or take the Button class, for the Windows forms Button UI element: it doesn't represent any particular button - it represents a button, as in any button. It defines a button as a type. It is the objects of this class that define the individual UI elements with specific labels and associated operations. It's a very powerful thing. The main idea here is reusability: because someone defined these classes like, String and Button, not as some specific string or button, but as abstractions that represent the concept of a string and a button, we are able to reuse their implementation code (the kind of data it can store, and more importantly the methods defined for them) in many different applications.
    Of course, there will be times when you need no more than one instance of a particular class, but even then you'll probably be able to reuse the class in a different app - so it's worth the separation.

  8. #8
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Static, Classes and Objects

    The concept of static members, and static classes, is somewhat less fundamental then the previous two.
    For static members (fields or methods), it simply means that the member marked as static belongs to the class (as opposed to belonging to a particular instance, as it otherwise would). Thus, it is shared among all instances of the given class - all of it's objects access the same data. In fact, in VB.NET, the equivalent of the static keyword is the Shared keyword. In C#, the choice of the keyword was taken from languages like C++ and Java.

    For example:
    Code:
    public class Hello
    {
        // I'm using auto-properties here for data members; 
        //  make sure to learn regular properties as well!
        
        public static string StaticMessage { get; set; }    
        public string InstanceMessage { get; set; }    
    
        public void SayHello()
        {
            Console.Write(StaticMessage);
            Console.WriteLine(InstanceMessage);
        }
    }
    
    
    // Somewhere in Main():
    Hello h1 = new Hello();
    Hello h2 = new Hello();
    Hello h3 = new Hello();
    
    Hello.StaticMessage = "Hi!";  // affects all, can be accesed only via Hello
    
    // these affect specific instances only
    h1.InstanceMessage = "And good morning!"
    h2.InstanceMessage = "Have a nice day!".
    h3.InstanceMessage = "Nice evening!".
    
    h1.SayHello();
    h2.SayHello();
    h3.SayHello();
    
    
    Console.WriteLine();
    
    Hello.StaticMessage = "Goodbye!";
    h1.SayHello();
    h2.SayHello();
    h3.SayHello();
    Output:
    Hi! And good morning!
    Hi! Have a nice day!
    Hi! Nice evening!

    Goodbye! And good morning!
    Goodbye! Have a nice day!
    Goodbye! Nice evening!


    When used with a class (when a class is declared as static), then the class effectively cannot be instantiated, and can only have static members. This can be useful for some utility classes, like the static Math class provided with the .NET Framework Library; you might have used Math; if not - you will at some point. In a way, it's like only being able to have a single "instance" of that class, global in scope (a Singleton).

  9. #9
    Join Date
    Aug 2009
    Posts
    12

    Re: Static, Classes and Objects

    Dear god this is a brain breaker...

    I suppose when the time comes to use it in actual code I'll understand it better then. I thank you guys for your help and I'll keep this bookmarked to come back to it.

  10. #10
    Join Date
    Aug 2009
    Posts
    12

    Re: Static, Classes and Objects

    Holy hell, I think I understand it all now.

    Classes are basically folders. They hold two files of two different types (variables and methods, either can be either static or instance.). Variables and methods can either be static (which means it can only be accessed by going directly through the class (class.method(); or class.variable = value) or instanced (which means they can only be accessed by creating an object of the class (class class1 = new class; ) and using that to access the variable/method (class1.variable = value; or class1.method(); ) to access it.

    All static and instanced information is copied to objects when they are created (class class1 = new class; will have all information that the original class has). However, all static variables that have values cannot be changed unless you use the class directly (class.variable = value; ). They cannot be changed via the object (class1.variable = value; ).

    Instanced variables can be accessed only by objects however. Static methods can only be accessed by going through the class (class.method(); ) and instanced methods can be accessed by objects. Instances variables and methods allow objects to differentiate themselves from one another. So take this for example:

    z1 is an object of zombie(which is the original class). z2 is the second object of zombie. Both z1 and z2 are zombies, however, they are different. z1 has the same methods and variables of z2 because they both came from zombie. However, z1 can only access the instanced variables which means it can only change the variables assigned to IT. To understand, z1.color = "green";. 'color' was a string created in the class zombie and that string was given to both z1 and z2. The string is an instance which means z1 and z2 can change it, but only for itself. When we declared the string color via z1 to be green, that means z1 is now green and z2 is unchanged. In order to change the color string of z2, we would have to access the instanced variable via z2.color = "value"; and change the color that way.

    Methods work the same way. Instanced methods only effect the object it was called upon. In class zombie, we have a method called walk. Each object (z1 and z2) have access to this method via z1.walk(); and z2.walk(); respectively. Walk basically commands the zombie to move a certain distance. Method is commanded by a random number, so z1 and z2 move a different distance each time. If walk was static, then it would effect both z1 and z2 the same way when they called them. z1 would walk 1 space and z2 also walks 1 space.

    EDIT: Also, sorry for double posting. I'm just so excited I finally got this down. xD
    Last edited by Deathscreton; March 17th, 2012 at 05:20 AM. Reason: fixing wink faces

  11. #11
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Static, Classes and Objects

    Quote Originally Posted by Deathscreton View Post
    Holy hell, I think I understand it all now.
    You are very close. But, there are a few important (and some less important) details.

    Quote Originally Posted by Deathscreton View Post
    Classes are basically folders. They hold two files of two different types (variables and methods, either can be either static or instance.). Variables and methods can either be static (which means it can only be accessed by going directly through the class (class.method(); or class.variable = value) or instanced (which means they can only be accessed by creating an object of the class (class class1 = new class; ) and using that to access the variable/method (class1.variable = value; or class1.method(); ) to access it.
    True, you can think of classes as "folders" for two kinds of class members (there are more than two, but these are the most basic). In the sense that class defines a space for those members to be in, and assigns a name for that space (organizes them into a class of a given name, between the '{' and '}'). You use the member access operator (the dot '.') to access those members. But that's as far as the analogy goes, it'll become clear in a few moments. The analogy of folders is better used to describe namespaces - people sometimes find them confusing, but they are nothing more than folders for classes. It helps us developers organize our classes into sets of related classes (maybe they are designed to work together on a similar task, or are made to solve similar type of problems, or are made by the same company). Think of boxes, containing other boxes.

    Quote Originally Posted by Deathscreton View Post
    All static and instanced information is copied to objects when they are created (class class1 = new class; will have all information that the original class has). However, all static variables that have values cannot be changed unless you use the class directly (class.variable = value; ). They cannot be changed via the object (class1.variable = value; ).
    Close. The main thing is, as far as instance data members go, they don't exist until an instance is created - only the specification of what should they be exist (what type, and the variable name). That's why classes are often described as blueprints, or molds. That's why I insisted on limiting the folder analogy. As for static members, the main thing to remember is that they are shared among all instances of the same class, and thus you can think of them as belonging to the class itself (rather than any one of the it's objects). In C#, you cannot access them via the object, because the C# design team decided so - they probably thought that decision will result in code that's a more easy to read and understand. C++, for example, also has static members, but there you can access them via the object. The basic idea is the same though - static members are shared among all class instances. So, that's the main point to remember about them.

    Now, before I answer your next question, there's another thing you must understand.
    Instance and static members can be accessed from within the class (from a member method), and from outside the class (from a method that is not a member of the given class).

    So, this code would be an example of outside access:
    Code:
    public static void Main(string[] args)
    {
        SomeClass a = new SomeClass();  // calling the constructor
        a.SomeOperation();  // calling a member method from the outside
    
        // here, it's assumed that Main() doesn't belong to SomeClass
    }
    From outside, you can only access those members that class lets you to (a class can have private members, accessible only from the inside.)
    Here's how an inside access looks like:
    Code:
    public class SomeClass
    {
        private int someDataMember = 256;  // not accessible from outside (private)
    
         public void SomeOperation()
        {
            // accessing the instance member from inside the class
            // when an object is created, and this method is then called,
            // the instance data member of that object will be changed
            someDataMember = someDataMember * 2;  
        }
    
        public void AnotherOperation()
        {
            SomeOperation();   // calling the previous method from inside the class
        }
    }
    OK, let me go on:
    Quote Originally Posted by Deathscreton View Post
    Instanced variables can be accessed only by objects however. Static methods can only be accessed by going through the class (class.method(); ) and instanced methods can be accessed by objects. Instances variables and methods allow objects to differentiate themselves from one another. So take this for example:

    z1 is an object of zombie(which is the original class). z2 is the second object of zombie. Both z1 and z2 are zombies, however, they are different. z1 has the same methods and variables of z2 because they both came from zombie. However, z1 can only access the instanced variables which means it can only change the variables assigned to IT. To understand, z1.color = "green";. 'color' was a string created in the class zombie and that string was given to both z1 and z2. The string is an instance which means z1 and z2 can change it, but only for itself. When we declared the string color via z1 to be green, that means z1 is now green and z2 is unchanged. In order to change the color string of z2, we would have to access the instanced variable via z2.color = "value"; and change the color that way.
    Close again. Everything is quite right, except for the static members. From inside the class, each of the objects can access any static member of it's class - that's why it's said that they are shared. So, for example, if an object uses a static member to do some calculation or show some output, the result of that will depend on what some other object has done with that same, shared static member previously, or what some outside method has done with the shared member accessing it via the class name.
    Quote Originally Posted by Deathscreton View Post
    Methods work the same way. Instanced methods only effect the object it was called upon. In class zombie, we have a method called walk. Each object (z1 and z2) have access to this method via z1.walk(); and z2.walk(); respectively. Walk basically commands the zombie to move a certain distance. Method is commanded by a random number, so z1 and z2 move a different distance each time. If walk was static, then it would effect both z1 and z2 the same way when they called them. z1 would walk 1 space and z2 also walks 1 space.
    Again, if shared (static) members are involved in any way, all are affected. For example, if an instance method, or a static method, changes a static member, all the other objects will be affected, in the sense that all of them share the same static member. Static methods, however, cannot access instance members, simply because they are defined on the class level, and thus there is no way for them to determine which of the instantiated objects should they use to access such members. With instance methods is easy - they access the members of that object on which they are called (remember how you call instance members from the outside). As static methods aren't called on objects, but on classes, they can't do that.

    Quote Originally Posted by Deathscreton View Post
    Method [ walk() ] is commanded by a random number, so z1 and z2 move a different distance each time. If walk was static, then it would effect both z1 and z2 the same way when they called them. z1 would walk 1 space and z2 also walks 1 space.
    How the zombie moves depends entirely on what the walk() method is written to do. If you make it so that it moves a zombie by a random amount, than that's what it'll do.
    A static method can only influence the data that is shared among all zombies (that is, the data declared to be static). In this scenario, each of the zombie objects would maintain it's own location. So, with respect what I said above, you couldn't move both of them by calling a static method. There are other ways to do that. But, if, for example, you wanted to have a global speed modifier that affects all the zombies, you could use a static member to achieve this. But, even in this case, there are other ways to do this.
    Static members (fields, methods, properties) are not used all that often.
    Some of the common uses would be:
    • utility methods - for example, the Point struct (an integer 2D point) has a static method Round() that takes a PointF (a floating-point 2D point), rounds its components, and returns the result as a new Point (integer components again).
    • "factory" methods - sometimes, it's convenient to use static methods, instead of constructors, to instantiate objects. Since you can give them any name, you can communicate from what and how the method creates the object. You can have the same kind of parameters in the parameter lists of two factory methods, that create the object in different ways. With constructors, the compiler wouldn't be able to tell which one to call. For example, the Image class has such static methods, called FromFile(), FromStream()...
    • other uses


    Note: The types I mentioned (Point, PointF, Image) are available as part of the .NET framework library.

  12. #12
    Join Date
    Aug 2009
    Posts
    12

    Re: Static, Classes and Objects

    I think I understand it all. I went and practiced some code using variables and the program seemed to come out just fine. Thanks again! That has to be the most confusing part of C#. xD

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured