Design for reaching variables of same class with different objects

+1 vote
asked Dec 27, 2015 by beyaz

I'm Android developper and stuck on some implementing design.Here is my basic design:

Class x extends a{

y obj = new y();
y obj2 = new y()
Class y extends a{

z obj3 = new z();

What i need:in obj1 need to reach obj2's obj3' function(setChecked)

What I did try: Solution try 1-)did class y to extend x instead of a but when I did try to reach obj2 it is different object where x object created so y object is different! Solution try 2-)did try use Singeleton pattern since it is only one object create. But as you know it should be static. But in android activity variables should not be created staticly,instead should be dynamicly change.


a : BaseAdapter

z : ToogleButton

What I'm trying: In android,I did implement navigation bar. Listview object have sub two ListView object, I used my solution with lower api support. In first sub listview object's Tooglebutton state changed,It should change sub second listview object tooglebutton.

2 Answers

0 votes
answered Dec 27, 2015 by sisyphus

Quick tip: for readability purposes it's best to start class names with a capital letter and make them slightly longer than 1 character, even for example purposes.

You don't generally want to access the private fields of one object from another object - that breaks encapsulation and makes it very difficult for you to change that field in any way because you can't really know who's referencing it.

what you need to do is to provide an accessor method on your y class which calls the relevant method on obj3 for you. This effectively encapsulates the obj3 field behind a behaviour of your y class.


Class MyClassX extends SomeClassA {
    private final MyClassY obj = new MyClassY();
    private final MyClassY obj2 = new MyClassY()

    public final void doSomeComplexStuff() {

Class MyClassY extends SomeClassA {
    private final MyClassZ obj3 = new MyClassZz();

    public final void setChecked(final boolean checked) {

So when you call obj2.setChecked(true) that call gets passed along to the instance of MyClassZ contained within obj2.

0 votes
answered Dec 27, 2015 by beyaz

After thinking carefully,I found for that solution which I only need reference adress of object. But in Java, there is no reference address of operator except one thinking. Passing object instance to another object,refer adress of that created object.Everything done with passed object effect passing object so that I pass obj2 variable to obj1 constructor so problem solved. But in that solution only obj1 can reach obj2 variables&function, obj2 can't reach to obj1. For mutual relation,I think creating class with singleton pattern on different page with get and set methods of that object will solve everything.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter