子クラスから親クラスのprotectedにアクセスできない
場合による
C#、C++、TypeScript
子クラス (自身)・孫クラス (自身の継承クラス)を介して、protectedにアクセスできる
Java
同一パッケージ内のクラス、継承したクラスからアクセスできる
Javaのprotectedは、Visual BasicのProtected Friendに近い?
同一パッケージ内のクラス、ってのがミソ?
I've only ever written one program in Java and that was about ten years ago, so I'm a bad person to ask about Java semantics.
However, my reading of section 6.6.2 of my 1996 copy of the JLS is that in your example, the semantics of "protected" do not apply because the two classes are in the same package.
If you read section 6.6.7, it describes the semantics of cross-package access to protected members via subclasses as being the same as I describe above.
Apparently in Java, "protected" means roughly what "Protected Friend" means in Visual Basic.
Stack OverflowのC#の例をTypeScriptで書いてみる
トランスパイルエラー
自分のクラスのインスタンスからしかアクセスできない、というメッセージが表示される
code:ts
class 親クラス {
protected プロパティ() {}
}
class My子クラス extends 親クラス {
error1(親: 親クラス) {
// Property 'プロパティ' is protected and
// only accessible through an instance of class 'My子クラス'.ts(2446)
親.プロパティ()
}
error2(Other子: Other子クラス) {
// Property 'プロパティ' is protected and
// only accessible through an instance of class 'My子クラス'.ts(2446)
Other子.プロパティ()
}
ok1(My子: My子クラス) {
My子.プロパティ()
}
ok2(My孫: My孫クラス) {
My孫.プロパティ()
}
}
class My孫クラス extends My子クラス {}
class Other子クラス extends 親クラス {}
Javaはアクセスできる
コンパイルエラー、実行時エラーなし
code:java
import java.util.*;
class 親クラス {
protected void メソッド() {
System.out.println("Hello");
};
}
class My子クラス extends 親クラス {
public void test(親クラス 親) {
System.out.print("親: ");
親.メソッド();
}
public void test(Other子クラス Other子) {
System.out.print("Other子: ");
Other子.メソッド();
}
public void test(My子クラス My子) {
System.out.print("My子: ");
My子.メソッド();
}
public void test(My孫クラス My孫) {
System.out.print("My孫: ");
My孫.メソッド();
}
}
class My孫クラス extends My子クラス {}
class Other子クラス extends 親クラス {}
public class Main {
public static void main(String[] args) throws Exception {
My子クラス My子 = new My子クラス();
My子.test(new 親クラス()); // 親: Hello
My子.test(new Other子クラス()); // Other子: Hello
My子.test(new My子クラス()); // My子: Hello
My子.test(new My孫クラス()); // My孫: Hello
}
}
refs
なぜこういう仕組みか?を説明している
いまいち理解できない