Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] Question about passing info between classes.

Started by brinmalice Aug 4, 2006 at 7:44 AM 1 replies 650+ views
Original Post
brinmalice
brinmalice
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]
Funkapotamus
Funkapotamus
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

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.
brinmalice
brinmalice
Thanks for the help.
I just wanted to be able to be able to grab x y coords for a graphic as well as the string for graphics to load out of the individual classes to be passed into my draw loop.

;)

Thanks again!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.