developer234
developer234

Reputation: 79

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");
        }
    }
}  

Upvotes: 0

Views: 4046

Answers (4)

Ian2thedv
Ian2thedv

Reputation: 2701

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());
    }
}

Upvotes: 1

nogard
nogard

Reputation: 9716

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).

Upvotes: 2

duckstep
duckstep

Reputation: 1138

You can make pObject static and access it as parentClassAction.pObject.

Upvotes: 2

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

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.

Upvotes: 0

Related Questions