0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

static キーワードについて

Posted at

なんとなく付けたりつけなかったりしていたので記憶のためにまとめておく


クラス直下に定義する変数、メソッドには2種類ある

◯インスタンスメンバ
→オブジェクトが個別に値を持つ
・インスタンス変数
・インスタンスメソッド
 
◯static メンバ
→それぞれのインスタンスが共通して参照する
static変数
staticメソッド

宣言・構文

◯変数
→データ型の前に記述
static int count;
 
◯メソッド
→戻り値の型の前に記述
static void display();

特徴、違い

◯インスタンスメンバ
→実行されると各オブジェクトの中に個々の領域として用意される(図:③)
 
◯static メンバ
→複数インスタンス化されても1箇所で領域が確保される(図:②)
→インスタンス化(しても)しなくても呼び出しが可能
 

メモリ領域の確保に違いがある

スクリーンショット 2025-06-18 7.01.12.png

呼び出し

「クラス名.static変数」
Student.counter;
「クラス名.staticメソッド名」
Student.display();

クラス内での両メンバ間のアクセス

class Test {
    int instanceVal;
    static int staticVal;

    int countA() {return instanceVal;}        //①
    int countB() {return staticVal;}          //②
    static countC() {return instanceVal;}     //③
    static countD() {return staticVal;}       //④
    static countE() {                         //⑤
        Test t = new Test();
        return t.instanceVal;
    }
}
①・・・インスタンスメソッド→インスタンス変数のためOK
②・・・インスタンスメソッド→static変数のためOK
③・・・staticメソッド→インスタンス変数のためNG
④・・・staticメソッド→stasic変数のためOK
⑤・・・staticメソッド→インスタンス変数のためNG
   ...ではなくTestクラスをインスタンス化し、
   t.インスタンス変数でアクセスしているためOK

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?