0

I have two classes in my main class(lets call them classA and classB).

Is there any chance to set classA variables within classB?

Something like that:

class classB {
    int indexB;

    classB() {
        indexB = 0;
        classA.index = indexB;
    }
}

thank you very much! greetings

4
  • Please specify the language, by using a tag and mentioning it in your question. Commented Oct 13, 2013 at 10:50
  • Do you really mean "in your main class"? I think you mean in your source file - the .java file. You might be using inner classes but that is a more advanced technique. Commented Oct 13, 2013 at 10:59
  • @geomanagas : java is tagged with question Commented Oct 13, 2013 at 10:59
  • @rkp yes but look at the timestamp on his comment and then look at the editing history. It was not tagged when he made that comment. Please pay attention. Commented Oct 13, 2013 at 11:01

3 Answers 3

1

Yes, you can directly assign public variables of classA as you did in your snippet, or declare a setter for private variables.-

classA

public setIndex(int index) {
    this.index = index;
}

classB

classAInstance.setIndex(indexB);
Sign up to request clarification or add additional context in comments.

1 Comment

yes, but it needs to be an instance (as implied above), or you need to declare the variable static, but that is not very OOP-like.
0

Yes, it is possible. Assuming index of the class classA is also package protected and classA is in the same package as classB then you can do something like that:

class classA {
    int index;
    classA() {}
    // OR
    classA(int index) {
        this.index = index;
    }
}

class classB {
    int indexB;
    classA classA;

    classB() {
        indexB = 0;

        classA = new classA();
        classA.index = indexB;
        // OR 
        classA = new classA(indexB);
    }
}

If both classes are in different packages you then you need a public setter for index in classA as demonstrated by ssantos (The second method I've shown, using the constructor, will work in this case too it the constructor is public).

It is however not very good to access members of other classes directly. Please use getters and setters for that, also please consider the java naming conventions: class should start with an uppercase letter, thus ClassA and ClassB.

Comments

0

The index has to be a static variable of class A.Then you can do this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.