Skip to content

Instantly share code, notes, and snippets.

@johobemax
Created July 28, 2010 09:37
Show Gist options
  • Save johobemax/493871 to your computer and use it in GitHub Desktop.
Save johobemax/493871 to your computer and use it in GitHub Desktop.
package animal; //animalパッケージ
public class Animal
{
protected String name; //protectedなので、packageが違っていても、サブクラスなら参照可能
protected String voice; //protectedなので、packageが違っていても、サブクラスなら参照可能
public Animal()
{
name = "動物";
voice = "がおー";
}
public String shout()
{
return voice;
}
}
import animal.Animal;
import dog.Dog;
public class AnimalTest
{
public static void main(String[] args)
{
Animal a = new Dog();
System.out.println(a.shout());
}
}
package dog; //dogパッケージ
import animal.Animal;
public class Dog extends Animal //Animalを継承するDogクラス
{
public Dog() //オーバーライドされたコンストラクタ
{
name = "犬"; //Animalクラスの、protected String name; を参照している
voice = "わん"; //Animalクラスの、protected String voice; を参照している
}
}
@johobemax
Copy link
Author

パッケージと、継承と、protectedのサンプル。

結果は==> わん

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment