In C# a static class is a class that, in addition to not supporting inheritance, can have any kind of type member a "normal" class can have except instance members.
Not so sure how static classes work in java, but based on the limited amount of java code I have seen, it's clear to me that they don't work quite the same way.
Can someone please enumerate the differences?
Static classes in Java are one of three kinds of nested classes provided by the language (the other two being non-static nested classes and function-scoped classes).
Static classes of Java behave the same way that nested classes of C#: they have access to static members of the enclosing class, but cannot access instance members without an additional reference to the enclosing object. In contrast, non-static nested functions can access instance variables, but you need an enclosing instance in order to be instantiated.
in C#
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors
in Java :
Only nested classes can be static.
can have static members in classes
In Java, you cannot have the outer most class as static. Only inner classes can be declared with the static modifier. Doing so prevents that inner class from having access to instance members of the outer class.
In C#, you can define the outer class with the static modifier, which makes it impossible to create instance variables of that class. These serve two different purposes. To create a similar effect in Java, you can define private no-args constructor. The singleton pattern implementation does so. Also in Java, can also create a class with all its members defined static, but that doesn't prevent creation of new instances.
Related
I took a look over this question and I was wondering the opposite situation. Why would be needed?
Someone said there that:
Why would you have a "shared method" that is in a class, not in a
module? Answer: To share it amongst instances of its class.
Well this it is clear why it would be necessary to use a static method within a non-static class. What about the opposite?
The opposite (instance method in static class) is impossible, at least in C#. It produces compile time error.
In Java, static methods work the same way in nested static class as they do in non-nested non-static classes.
In the example given the main(String[] args) has to be static
If you have a method which doesn't use this it is preferable (and simpler) to make the method static so its clear the method doesn't need an instance.
A class can only be declared static when it is a nested class - you do that when you want that nested class to be accessible without having to create an instance of the containing class.
Apart from that, it is just a normal class, which can have an instance state (non static variables) and you would use non static methods in that class like you would in any other class...
For example, HashMap contains a static nested class Entry which has some non-static methods.
ps: you just added the C# tag - my answer relates to your original question, tagged Java.
Static class cannot be instantiated so there is no use of declaring non static methods inside a static class.
Hello All:
what is difference making full class static and making functions of the class as static?
I mean are there any performance issues?
The feature of static classes was only introduced in C# 2. The CLR doesn't really have such a concept. A static class in C#:
Has no constructors, not even a default parameterless one
Is sealed: it can't be subclassed
Is abstract: you can't create instances of it (which also follows from there being no constructors)
Can only contain static members
Can't be used as a parameter or variable type or a generic type argument etc.
Can't specify any base type other than object
There's no performance difference between using static members of a "normal" class and using ones in a static class. It's primarily a way of stating the intention that there should never be any instances of this class, without having to provide a private and never-called constructor, and forcing the compiler to check that you're not trying to use it as a normal class.
Note that extension methods (introduced in C# 3) can only be declared in a top-level, non-generic static class.
It has two implications:
All methods of the class must also be static.
You can't make an instance of that class other places in your code.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to Use Static Classes in C#
why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.
thanks
A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.
Generally I would advise you not to write static classes.
There are cases where you want them though
Extension methods have to live on static classes. This is the best reason to have a static class.
If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.
Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.
Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.
A static class cannot contain any constructors, only a static constructor that is called first time one of its members is accessed.
That is basically the difference. Performance wise we also get another for free by the compiler since it can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are also sealed and therefore cannot be inherited.
http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Another valid point is that Extension Methods has to be declared in a static class
http://en.wikipedia.org/wiki/Extension_method
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method.
In static class all method all static. we can not declare normal method in static class.
differences between static class and normal class.
We can not create object of static class, when we use method of static class just use classname.MethodName but in normal class we have to first create object of class then we can access method of normal class.
static class ex.
Class1.functionname();
normal class ex.
Class1 cs = new class1();
cs.functionname();
functionname should not be private.
The difference is that you can't instantiate a static class. So you'd make a class static if you don't want it ever being instantiated. This is useful in cases when you're dealing with threading issues, and you want all threads to be guaranteed to use the same instance of your class.
A more philosophical scenario is when you have a class that doesn't need to be instantiated, such as (for example) you're building a database application and you create one class to do all the database access stuff. It's basically just a collection of methods. Then making the class static simply becomes a step to make your design more consistent.
I was asked the above question in an interview. Could you please explain the differences? ( performance - memory - usage - when to use which ? )
Thank you,
Erkan
Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.
A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:
Provide a factory method for creating an instance of that type;
Provide helper functionality that does not require an instance of the type;
Also, as mentioned already, extension methods can only be declared on a static class.
I assume you were asked for the differences?
A static method on a static class can be used to define an extension method. A static method on a non-static class cannot.
In terms of performance and memory usage; precisely nothing. Having a static class means you know there are no instances, but back in 1.1 having a private constructor sufficed. Use a static class if it simply makes no sense to have an instance! (utility classes etc)
When you are providing utility functions and all your methods are static, I recommend you use static methods in a static class.
When you want to provide utility methods that just deal with your instance, I recommend you use static methods in a non-static class. For example:
var myClass = MyClass.Create();
var myClass = MyClass.Parse("serialized.MyClass");
In terms of memory, there is a slight difference: the static method in a non-static class will be allocated only when the first instance of that type is created, and deallocated when the last instance of that type is deallocated. Static methods on instance objects are very useful when we have collections of objects of the same type in order to decrease the amount of memory used. The drawback of using static methods is that they are not unit testable, so before creating a static method, an eye should be kept on how it will affect the code coverage.
One major difference I faced when deciding whether to go with normal class with all static methods or, use a static class, is that a normal class supports interface implementation, where as static class does not.
I use static class only when I am sure it will be a collection of static functions (usually helper functions), and will never be in the main stream of program. I promote interface programming, for dependency injections, unit testing etc. So, for main flow of program, I use normal class with static methods.
Ref: MS Docs
In C# what is the difference between:
public static class ClassName {}
And:
public class ClassName {}
Firstly, a comment on an answer asked about what "static" means. In C# terms, "static" means "relating to the type itself, rather than an instance of the type." You access a static member (from another type) using the type name instead of a reference or a value. For example:
// Static method, so called using type name
Guid someGuid = Guid.NewGuid();
// Instance method, called on a value
string asString = someGuid.ToString();
Now, static classes...
Static classes are usually used as "utility" classes. The canonical example is probably System.Math. It doesn't make sense to create an instance of math - it just "is". A few rules (both "can" and "can't"):
Static classes always derive from object. You can't specify a different base type, or make the static class implement an interface.
Static classes can't have any instance members - all variables, methods etc must be static.
Static classes can't declare any instance constructors and the compiler doesn't create a parameterless constructor by default. (Before static classes came in C# 2.0, people would often create an abstract class with a private constructor, which prevented instantiation. No need here.)
Static classes are implicitly abstract (i.e. they're compiled to IL which describes an abstract class) but you can't add the abstract modifier yourself.
Static classes are implicitly sealed (i.e. they're compiled to IL which describes an sealed class) but you can't add the sealed modifier yourself.
Static classes may be generic.
Static classes may be nested, in either non-static or static classes.
Static classes may have nested types, either non-static or static.
Only static, top-level non-generic classes can contain extension methods (C# 3.0).
A static class cannot be instantiated, and can contain only static members. Hence, the calls for a static class are as: MyStaticClass.MyMethod(...) or MyStaticClass.MyConstant.
A non static class can be instantiated and may contain non-static members (instance constructors, destructor, indexers). A non-static member of a non-static class is callable only through an object:
MyNonStaticClass x = new MyNonStaticClass(...);
x.MyNonStaticMethod(...);
public static class ClassName {}
A static class is just like a global variable: you can use it anywhere in your code without instantiating them.
For example: ClassName. After the dot operator, you can use any property or function of it.
public class ClassName {}
But if you have non-static class then you need to create an instance of this class.
For example:
ClassName classNameObject = new ClassName();
A static class also can not be inherited from, whereas a non-static class with static members can be inherited from.
All methods/properties in a static class must be static, whereas a 'normal' class can contain a mix of instance and static methods.
You can't instantiate (create objects of) a static class. And it can only contain static members.
Example: System.Math
Static class can contain static members only.
Static member can be used without instantiating a class first.
Static classes and members are used to create data and methods that can be accessed without creating an instance (using the new keyword, they cannot have a constructor) of the class.
Static classes can be declared when there is no dependence on the its own object identity, so a static class must contain only static members.
This classes are loaded by the CLR when the program or namespace containing the class is loaded.
They are also sealed, cannot be inherited from.
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html - very good article on this. This is for Java. But i think concept should should same in C# too.
Static variable in c
a variable local to a class as auto variables
but static variable do not disappear as function is no longer active.Their values persist.If control comes back,static variables have same value
static function in c
functions that are not visible to functions in other files.
*static data members in cpp *
data members can be variables or functions in cpp
static applies to both data members
the class itself can be static
"There is only one copy of static data memberss shared by all objects in that class"
static data members can access only static data members
static class
this class cannot instantiate objects
Most importantly, "A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides." - From Microsoft