dポイントプレゼントキャンペーン実施中!

たとえば、
class A {
private int width;

public A(){
this.width=3;
}
public int getWidth(){
return width;
}

public void setWidth(int width){
this.width=width;
}
}
--------------------------------
class B extends A {
String name;

public B(){
this.name="あきら";
}
}
--------------------------------
class TestAB{
public static void main(String[] args){

B b = new B();
B b2= new B();

System.out.println(b.getWidth());

b2.setWidth(5);
System.out.println(b2.getWidth());

System.out.println(b.getWidth());
}
}


というのがあったとして、ある参考書では「privateなフィールドは継承されない」と書いてありました。
でも、これってwidthに直接アクセスして値を変更できないだけであって、
widthは継承されてるのではないですか?

B型のb専用、b2専用のwidthがあるのではないですか?


ちょっと頭がこんがらがってきました。。

A 回答 (2件)

アクセスできないフィールドとして継承します。




public class a {
public int aaa=10;
}

public class b extends a {
private int aaa=20;
}

public class c extends b {
public static void main(String[] args) {
b zzz = new b();
System.out.println(zzz.aaa);

}
}

は、コンパイルエラーになりますが、class b を

public class b extends a {
}

と書き換えると class a の aaa フィールドが見えるようになります。
このあたりを味わってみてください(^^; おもしろいですよ。
    • good
    • 0
この回答へのお礼

回答ありがとうございました。
やっぱり、アクセスできないフィールドとして継承されてるのですよね。

お礼日時:2011/06/22 16:02

継承先に同名のフィールドを定義して


コンパイルがとおるかどうか調べると
分かる。
    • good
    • 0
この回答へのお礼

回答ありがとうございました。

コンパイルとおりました。
継承されてる・・・っていうことですよね?

お礼日時:2011/06/22 16:10

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!