C#のクラス変数と静的変数
静的変数は、インスタンスを作成せずにクラスを呼び出すことで値を取得できるため、定数の定義に使用されます。静的変数は、メンバー関数またはクラス定義の外部で初期化できます。クラス定義内で静的変数を初期化することもできます。
例
using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;
public void count() {
num++;
}
public int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
} 出力
Variable num for s1: 6 Variable num for s2: 6
クラス変数は(設計の観点から)オブジェクトの属性であり、カプセル化を実装するためにプライベートに保たれます。これらの変数には、パブリックメンバー関数を使用してのみアクセスできます。
例を見てみましょう-
例
using System;
namespace BoxApplication {
class Box {
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len ) {
length = len;
}
public void setBreadth( double bre ) {
breadth = bre;
}
public void setHeight( double hei ) {
height = hei;
}
public double getVolume() {
return length * breadth * height;
}
}
class Boxtester {
static void Main(string[] args) {
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
} 出力
Volume of Box1 : 210 Volume of Box2 : 1560
-
Javaスタティック
Java静的キーワードの使用方法 Javaでクラスを操作している場合、通常、そのメンバーにアクセスする前に、クラスのインスタンスを作成する必要があります。ただし、クラスのインスタンスを作成せずにクラスメンバーを定義したい場合があります。 そこで登場するのがJavastaticキーワードです。Javastaticキーワードは、クラスのインスタンスを作成せずにアクセスできるクラスメンバーを定義するために使用されます。 このチュートリアルでは、例を使用して、Javastaticキーワードの基本とJavaプログラムでの使用方法について説明します。 Javaクラス Javaでは、クラスはオブジェ
-
android studioの静的変数をどこでどのように使用しますか?
この例は、AndroidStudioで静的変数を使用する方法と場所について示しています。 ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します ステップ2 −次のコードをres / layout/activity_main.xmlに追加します。 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http:/