Search code examples
javaclass-design

Java: Access public member from a non-related class?


The following Java code is a stripped down example of the code I need. My question is, how do I access someInt from inside class Second? Note that Second implements another class, so I can not just pass someInt in.

package test1;

public class First {
    public int someInt;

    public static void main(String[] args) {
        First x = new First();
    }

    public First(){
        someInt = 9;
        Second y = new Second();
    }
}


class Second implements xyz{
    public Second(){}

    public void doSomething(){
        someInt = 10; // On this line, the question lies.
        System.out.println(someInt);
    }
}

Solution

  • You can't access First's someInt field in Second because Second isn't an inner class of First. The changes below would fix your problem.

    package test1;
    
    public class First {
        public int someInt;
    
        public static void main(String[] args) {
            First x = new First();
        }
    
        public First(){
            someInt = 9;
            Second y = new Second();
        }
    
        class Second {
            public Second(){
                someInt = 10;
                System.out.println(someInt);
            }
        }
    }