static
- 全部のインスタンスから共通して使う変数やメソッドを作りたいとき
- クラスの関連する便利なメソッドをまとめたいとき
class Student{
int counter = 0;
Student(){
counter++;
}
}
stu1[] => couter 0 → 1
stu1[] => couter 0 → 1
インスタンス内の変数では無理!
全インスタンスが共通して使える変数が必要!
Static変数 Staticメソッド
- 全インスタンス変数が使えるメンバ変数やメソッドを定義するには、staticを指定する
- オブジェクトを生成しなくても利用できる
⇨ クラス名.変数[メソッド]名と記述する
Sample.java
class Student {
static int counter = 0;
counter++;
static void display(){
System.out.println(counter + "人です");
}
}
design(設計クラス).java
class Student4{
String name:
int counter = 0;
Student4(String n){
name = n;
counter++;
System.out.println(name + "さんをインスタンス化しました");
}
void display(){
System.out.println(counter + "人です");
}
}
//上記のコードに static を使う ※インスタンス化しなくても呼び出せる
class Student4{
String name:
static int counter = 0;
Student4(String n){
name = n;
counter++;
System.out.println(name + "さんをインスタンス化しました");
}
static void display(){
System.out.println(counter + "人です");
}
}
execution(実行用).java
class StuSample {
public static void main(String[] args) {
Student4 stu1 = new Student4("Michael");
stu1.display ();
Student4 stu2 = new Student4("Kenny");
stu2.display ();
}
}
//上記のコードに static を使う ※インスタンス化しなくても呼び出せる
class StuSample {
public static void main(String[] args) {
Student4 stu1 = new Student4("Michael");
Student4.display ();
Student4 stu2 = new Student4("Kenny");
Student4.display ();
}
}
カプセル化
- アクセス修飾子でクラス・メンバ変数・メソッドの公開範囲を指定できる
修飾子 | 同クラス | 同パッケージ | サブクラス | 他 |
---|---|---|---|---|
public | ○ | ○ | ○ | ○ |
protected | ○ | ○ | ○ | |
なし | ○ | ○ | ||
private | ○ |
Sample.java
class Student {
private int score;
public void setScore(int s){
score = s;
}
}
⬇︎
⭕️ stu.setScore(80);
❌ stu.setScore = 80;
- メンバ変数は隠蔽(private)して、クラスとメソッドは公開(public)する設計
をカプセル化と呼ぶ ⇨ 代入処理 修正範囲
design(設計クラス).java
public class Student5{
private String name:
int counter;
//コンストラクタ
public Student(String n){
name = n;
public void setScore(int $){
if(0 <= $ && $ <= 100) {
score = $;
}else{
System.out.println(name + "さんの点数が範囲外です");
score = 0;
}
void display(){
System.out.println(name + "さん" + score + "点");
}
}
execution(実行用).java
class StuSample5 {
public static void main(String[] args) {
Student5 stu1 = new Student4("Michael");
stu1.setScore (80);
stu1.display ();
Student5 stu2 = new Student4("Kenny");
stu2.setSocre (-50);
stu2.display ();
}
}
参考サイト
static変数、staticメソッドの使いどころやメモリ内の動き【Java入門講座】3-7 static
アクセス修飾子の使い方とカプセル化のメリット【Java入門講座】3-8 カプセル化