// パッケージmypackage1内ã®MyClass.java
package mypackage1;
// MyClassクラスを定義
public class MyClass {
// protectedãªãƒ¡ã‚½ãƒƒãƒ‰
protected void myProtectedMethod() {
System.out.println("This is a protected method.");
}
// protectedãªå¤‰æ•°
protected int myProtectedVariable = 42;
// コンストラクタ
protected MyClass() {
System.out.println("MyClass constructor called.");
}
}
// パッケージmypackage2内ã®åˆ¥ã®ã‚¯ãƒ©ã‚¹
package mypackage2;
import mypackage1.MyClass;
// mypackage1ã®MyClassを継承ã—ãŸã‚¯ãƒ©ã‚¹
public class AnotherClass extends MyClass {
public static void main(String[] args) {
// myProtectedMethodã«ã‚¢ã‚¯ã‚»ã‚¹
new AnotherClass().invokeProtectedMethod();
// myProtectedVariableã«ã‚¢ã‚¯ã‚»ã‚¹
new AnotherClass().accessProtectedVariable();
// protectedコンストラクタã«ã‚¢ã‚¯ã‚»ã‚¹
new AnotherClass().createInstance();
}
// protectedメソッドを呼ã³å‡ºã™ãƒ¡ã‚½ãƒƒãƒ‰
public void invokeProtectedMethod() {
myProtectedMethod();
}
// protected変数ã«ã‚¢ã‚¯ã‚»ã‚¹ã™ã‚‹ãƒ¡ã‚½ãƒƒãƒ‰
public void accessProtectedVariable() {
System.out.println("Protected Variable: " + myProtectedVariable);
}
// protectedコンストラクタを呼ã³å‡ºã™ãƒ¡ã‚½ãƒƒãƒ‰
public void createInstance() {
MyClass instance = new MyClass();
System.out.println("Instance created.");
}
}
ã“ã®ä¾‹ã§ã¯ã€mypackage2内ã®AnotherClassãŒmypackage1内ã®MyClassを継承ã—ã¦ã„ã¾ã™ã€‚ãれã«ã‚ˆã‚Šã€AnotherClassã‹ã‚‰MyClassã®protectedメソッドや変数ã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãã¾ã™ã€‚
protected修飾åã¯ã€åŒã˜ãƒ‘ッケージ内ã§ã‚れã°ã‚¢ã‚¯ã‚»ã‚¹ãŒå¯èƒ½ã§ã‚りã€ã•らã«ã‚µãƒ–クラスã‹ã‚‰ã‚‚アクセスãŒå¯èƒ½ã§ã™ã€‚ã“ã®ãŸã‚ã€AnotherClassãŒMyClassを継承ã—ã¦ã„ã‚‹ã“ã¨ã§ã€mypackage2内ã‹ã‚‰mypackage1ã®MyClassã®protectedメンãƒãƒ¼ã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãるよã†ã«ãªã‚Šã¾ã™ã€‚
「014 継承ã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント