+ 3
What is a static class? Explain with example.
6 ответов
+ 23
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. Because there is no instance variable, you access the members of a static class by using the class name itself.
Imagine, the logo of vivacell. It is static as for every single branch of vivacell, the logo is the same. There is only 1 STATIC logo for every vivacell branch.
+ 4
Great question, Tanmeya.
Let's look into more than you asked for ;-)
There are three different classes;
Public, private and protected.
Down below is a script I scratched down just real quick to easier display and relate. :)
Classes B, C and D all contain the variables x, y and z. It is just a question of access.
Simply about usage of protected and private access.
The script:
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };
};
class C : protected A
{
// x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };
};
class D : private A
{
// 'private' is default for classes { // x is private // y is private // z is not accessible from D };
Dr.
+ 1
A static class can be seen as a class of which only one object exists. This object cannot be instantiated, can be used directly and has the name of the class itself.
Applies to C#:
System.Math is a static class. There is no need to instatiate it and you wouldn't even be able to do so. It contains members like PI (in this case a constant, not a variable), and Methods like Min(...) or Pow(...).
Example Code in C#:
//Start of code
using System;
namespace FooBar
{
///<summary>
///Our own static class
///</summary>
static class Example
{
//some members
public const byte ANSWER = 42;
public static int CurrentYear = 1984;
//some methods
public static void SayHi()
{
Console.WriteLine("Hi!");
}
public static void SayHi(string name)
{
Console.WriteLine(quot;Hi, I'm {name}!");
}
}
class Program
{
static void Main()
{
//use of the class without instantiating an object
Console.WriteLine(Example.ANSWER);
int foo = Math.Max(Example.ANSWER, Example.CurrentYear); //also using the System.Math class, another static class
Example.SayHi("May");
}
}
}
//End of code
0
u can not create the instance of static class u can call it by its name.
0
Static class is a bunch of methods library. Just include the class and use its methods directly.