1

I am currently working on a hibernate project(EJB and JSF), and i have multiple java classes. The data of parent is being change in the front end with JSF, however, it is not updating in the child class. I need to access the data in the child class to do some calculation. Any Ideas as to how to pass the value of a variable from a parent class to a child class?

Thanks in advance

Example:

Parent class

public class parent {

    private String x = "a+";


    public String getx(){
         return x;
    }


    public void setx(String x){
         this.x = x;
    }

}

child class

public class child extends parent{
    private String z;

    public String getZ(){
        System.out.print(getx());
        return z;
    }
 }

main class

public static void main(String[] args) {

        parent p = new parent();

        System.out.println("Original" + p.getx());

        p.setx("z");

        System.out.println(" Add z" +p.getx());

        child c = new child();

        System.out.println("child getx" +c.getx());


        p.setx("zZ");
        System.out.println("child getz" +c.getZ());
    }
}

result. Original a+

Add z z

child getx a+

a+child getz null

4

2 に答える 2

2

ここで何を期待しているのか理解できません。すべてが正常に機能しています。

あなたの例では、 を呼び出すことはありませc.setXa+pはまったく別のオブジェクトを指し、 とは関係ありませんc。したがって、呼び出しp.setxは には影響しませんc。を設定したい場合はc.x、 を呼び出してc.setx("z")ください。ポリモーフィズムにします。 childextendsであるため、 のインスタンスでparent宣言されたメソッドを呼び出すことができます。parentchild

于 2012-12-06T04:43:58.450 に答える
1

2 つの異なるオブジェクトに「z」を設定していcますp。'c.getZ()が戻るzZには、 を呼び出す必要がありますc.setx("zZ")

于 2012-12-06T04:44:03.287 に答える