简体   繁体   中英

Java Inheritance: instance of object from parent class same for 2 child classes

What I'm trying to do is instantiate an object in the parent class called "pObject" (assume the type to be protected Boolean). One child class which extends the parent class sets "object" to "true". The other child class which also extends the parent class will check to see if "object" is set to true.

Is this possible in Java?

public abstract class parentClassAction{

    protected Boolean pObject;
}

public class childClass1Action extends parentClassAction{

    super.pObject = true;
}  

public class childClass2Action extends parentClassAction{

    if(super.pObject!=null){
        if(super.pObject == true){
            System.out.println("Success");
        }
    }
}  

您可以将pObject设为静态并将其作为parentClassAction.pObject访问。

You can access non private fields of a super class using the syntax:

super.myBoolean = true;

Note: If the field has the default visibility (absence of modifier) it is accessible only if the sub class is in the same package.

Edited: I add information due to the new code added to the question. It seems that you like to check a variable from two different objects. It is possible only if that variable is static. So declare it as protected static in the parent class. The rest of code rest the same.

If you have 2 different instances of subclasses - they do not share any state. Each of them has independent instance of pObject, so if you change one object it will not be seen in another one.

There are many ways to solve your problem. The easiest way: you can make this field pObject to be static - it will work for simple example, but this can be also serious limitation (if you want to have more than one instance of pObject).

Yes. If pObject is static it will be shared:

public class Legit {

    public static abstract class A {
        protected static Boolean flag;
    }

    public static class B extends A {
        public void setFlag(boolean flag) {
            super.flag = flag;
        }
    }

    public static class C extends A {
        public boolean getFlag() {
            return super.flag;
        }
    }

    public static void main (String [] args) {
        B b = new B();
        C c = new C();

        b.setFlag(true);
        System.out.println(c.getFlag());
        b.setFlag(false);
        System.out.println(c.getFlag());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM