Java 从父类对象设置所有子类变量

Java 从父类对象设置所有子类变量,java,Java,我有两个类A和B,它们的结构如下 Class A() { Integer a1; Integer a2; } Class B() extends A { Integer b1; } 如何设置B类的所有变量a1和a2?它们可以是A类对象的2个以上的对象 如果你想从父母那里访问孩子,答案很简单:你不能。父类可能有多个子类,因此必须进行引用,因为A没有B的变量,是B从A继承了变量 相反,您可以实例化该类并将其作为普通类访问 B b = new B(); b.b1 = 1

我有两个类A和B,它们的结构如下

Class A() {
    Integer a1;
    Integer a2;
}

Class B() extends A {
    Integer b1;
}
如何设置B类的所有变量a1和a2?它们可以是A类对象的2个以上的对象

如果你想从父母那里访问孩子,答案很简单:你不能。父类可能有多个子类,因此必须进行引用,因为A没有B的变量,是B从A继承了变量

相反,您可以实例化该类并将其作为普通类访问

 B b = new B();
 b.b1 = 1;
如果您的意思是从子类访问父类,则可以使用super关键字调用超类:

super.a1 = 3; // must execute from B class
由于java不允许多重养育,这个超级类不能与其他任何人交流

你可以做:

B b = new B();
b.a1 = 3;
b.a2 = 4;

假设A和B都在同一个包中,让我们在下面的例子中看到这一点

案例1:

A aReference = new A()
aReference.a1 = 1;
aReference.a2 = 2;
b1 is not present in the object so can not be set.
案例2:

A aReference = new B(); //reference of parent class and object of child class.
aReference.a1 = 10;
aReference.a2 = 20;
b1存在于对象中,但不可直接访问,因此需要类型转换

((B)aReference).b1 = 30;
案例3:

B bReference = new B();
bReference.a1 = 10;
bReference.a2 = 20;
bReference.b1 = 30;
案例4:

Suppose you want to modify it from inside a method of B

 class B extends A{
     ....
    public void someMethod(){
       super.a1 = 10;
       super.a2 = 20; 
       b1 = 40;
    } 
 } 
案例5:

If you want to modify the values of the state of child from parent class

public class A{

     public void someMethod(){
         ((B)this).b1 = 10;
         a1 = 20;
         a2 = 30;
    }
}
**第五点是非常糟糕的做法。父类不能知道子类。
***您应该使用setter方法修改状态并将状态保持为private,因为op要求使用父对象引用设置子类变量。你可以试试这个

代码示例:


在这里,我们将子类对象强制转换为父引用,并使用该引用更改变量数据

您的意思是要使用实例A中的值创建实例B,还是将A中定义的变量设置为B的实例?另外,B类扩展A是不正确的,应该是B类扩展A。请准确解释您想要什么,我现在还不清楚。看看是否需要。
If you want to modify the values of the state of child from parent class

public class A{

     public void someMethod(){
         ((B)this).b1 = 10;
         a1 = 20;
         a2 = 30;
    }
}
class A {
    Integer a1=5;
    Integer a2=6;
}

class B extends A {

}

public class Inherit {

    public static void main(String[] args) {

        A obj = new B();     //casting
        A obj2=new A();

        obj.a1 = 10;
        obj.a2 = 12;


        System.out.println("value of a1 in class A :"+obj2.a1+" & value of a2 in class A :"+obj2.a2);
        System.out.println("value of a1 in class B :"+obj.a1+" & value of a2 in class B :"+obj.a2);
    }

}