what are the main differences between a Java/C# static class?
Asked Answered
S

3

19

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?

Sensory answered 30/1, 2013 at 3:22 Comment(3)
#1512147Gestapo
@SeanF No, that's not it: this question asks about a different thing.Wedekind
Your question is already been answered here. [here][1] [1]: #295724Astronomy
W
14

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.

Wedekind answered 30/1, 2013 at 3:28 Comment(0)
G
6

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

Groggery answered 30/1, 2013 at 3:28 Comment(0)
M
3

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.

Manchukuo answered 30/1, 2013 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.