[java] Question about passing info between classes.
I have 3 classes, the second of which instantiates a class that I need to be able to get access to from the 1st class. Is there any way to pass the class name to another class so I can get access to it or do I have to make intermediate methods to pass the required information to the 1st class?
[Edited by - brinmalice on August 4, 2006 8:33:09 AM]
1) You could create static methods in the 3rd class to gain access to it anywhere.
2) You could setup methods in the second class to return a reference to the third.
3) You can reference 'public static' data members by referring to the class name
It depends on what you're trying to do. Generally, you'd want to do things the second way unless you have a good reason to need the others. It's very easy to write terrible spaghetti code if you start referencing static members from all over the place.
2) You could setup methods in the second class to return a reference to the third.
3) You can reference 'public static' data members by referring to the class name
public class ClassOne { public static void main(String[] args) { ClassTwo two = new ClassTwo(); // Option 1 - Static System.out.println(ClassThree.getValueStatic()); // Option 2 - By reference ClassThree three = two.getClassThree(); System.out.println(three.getValue()); // Option 3 - Static by name System.out.println(ClassThree.value(); }}public class ClassTwo { private ClassThree three; public ClassTwo() { three = new ClassThree(); three.setValue(100); } public getClassThree() { return three; } }public class ClassThree { public static int value = 0; public ClassThree() {} public void setValue(int value) { this.value = value; } public int getValue(){ return value; } public static int getValueStatic() { return value; }}
It depends on what you're trying to do. Generally, you'd want to do things the second way unless you have a good reason to need the others. It's very easy to write terrible spaghetti code if you start referencing static members from all over the place.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement