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?

Javaのアクセス修飾子(public / protected / default /private)を分かりやすく解説

0
Last updated at Posted at 2026-01-11

Javaには、クラス・メソッド・変数の公開範囲を制御するアクセス修飾子がある。

修飾子 同一クラス 同一パッケージ サブクラス 他クラス
public
protected X
(default) X X
private X X X

public(すべてのクラスからアクセス可能)

public class Sample {
	public String name;
}

protected(継承関係でアクセス可能)

//親クラス
class Animal {
	String name;
	void walk() {
		System.out.println("散歩に行きます");
	}
	
}

//子クラス
class Dog extends Animal {
	void bark() {
		System.out.println("ワン!");
	}
}

//活用
Dog myDog = new Dog();
myDog.name = "くろまめ";
myDog.walk();
myDog.bark();

実行結果

散歩に行きます
ワン!

(default) (修飾子なし)

//Apple.java
package com.example.fruit;
public class Apple {}

//Banana.java
package com.example.fruit;
class Banana {} //defaultは修飾子なし

//Negi.java
package com.example.vegetable;
import com.example.fruit.Apple; //
import com.example.fruit.Banana; // エラー。defaultは他のパッケージからimport不可

class Negi {
  Apple apple = new Apple();
  Banana banana = new Banana(); //エラーとなる
  
}



private(同一クラス内のみ)

主にGetter / Setterで使う。
Getter:値を「取得する」メソッド
Setter:値を「設定する」メソッド

public class Person {
    private int age;

  //get + 変数(頭文字は大文字)
    public int getAge() {
        return age;
    }

    //set + 変数(頭文字は大文字)
    public void setAge(int age) {
        //this.ageは上記のprivate int age;のage
        //ageは上記のpublic void setAge(int age)のage
        this.age = age;
    }
}

参考サイト

https://qiita.com/yummy888/items/b92b3a058f71b8353179
https://blog.naver.com/live_sol/224048642301

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?