Java实现子类之间获取到相同父类的值

许多时候,我们的子类都拥有相同的父类,有时候,我们想要子类之间的值能够相互共享,那么就可以通过下面的方式实现了。

思路:

1、给父类加一个type字段,用来区分是父类自己的对象还是子类对象。

2、在子类1set值时,如果type为page时,给父类赋值。

3、在子类2get值时,如果type为page时,得到父类的值。

代码

父类

@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class ParentData {
    /**
     * 父类类型,page,view
     */
    @NonNull
    private String type;
    /**
     * 父类值
     */
    private String value;

    /**
     * 父类对象
     */
    private ParentData parentData;


    public String getValueByType(){
        if(type.equals("page")){
            return value;
        }
        return parentData==null?"":parentData.getValueByType();
    }

    public void setValueByType(String value){
        if(type.equals("page")){
            this.value=value;
        }else{
            if(parentData!=null){
                parentData.setValueByType(value);
            }
        }

    }
}

 

 子类1

public class ChildrenData1 extends ParentData{
   public ChildrenData1(){
        super("view");
   }
}

子类2

public class ChildrenData2 extends ParentData{
    public ChildrenData2(){
        super("view");
    }
}

main方法

public class testMain {
    public static void main(String[] args) {
        ParentData parentData=new ParentData("page");
        ChildrenData1 childrenData1=new ChildrenData1();
        childrenData1.setParentData(parentData);
        childrenData1.setValueByType("我是子类1传入的值");
        System.out.println(childrenData1.getValueByType());
        System.out.println(childrenData1.getValue());
        ChildrenData2 childrenData2=new ChildrenData2();
        childrenData2.setParentData(parentData);
        System.out.println(childrenData2.getValueByType());
        System.out.println(childrenData2.getValue());

    }
}

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值