Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

In java, how do I access variables from one class in another?

I have two files, Main.java and Tickers.java

in Main.java I have public class Main and public static void main(String[] args)

in Tickers.java I have public class Tickers and public Tickers

in public class Main I have declared one variable, public double CarLength

I want to access CarLength in Tickers.java I have already tried

Main Variables = new Main();

CarLength = Variables.CarLength;

in Tickers.java but that does not display the value of the variable

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    You have the wrong idea of how to do this.

    The main method is the method that the program starts. You should use this only to start a program.

    Without seeing your entire code it is hard to say what you are doing.

    But, you should either send the car length as an argument to the constructor of the Tickers class.

    BUt, if you want to do it your way, you would have something like this in your Main class.

    public <datatype> CarLength;

    But, you should remove the constructor of the Main class and only have the main method in the Main class. In this main method, you want to create a new Tickers class and pass the car length to either the constructor, or a method that sets the car length.

    If at all possible, could you provide the entire code of your 2 classes to show what you are trying to do. Here is a help page to show you how to add extra details to your question:

    http://help.yahoo.com/l/us/yahoo/answers/ask/add_d...

  • 5 years ago

    Composition. You cant access the getAlbum() from the Album class cause that will break the rule of encapsulation. Hence your Album class must be composed of a Photo object to allow this operation. i.e. you need to define a Photo object in your Album class. Using this Photo object, you can call your getAlbum() method. Since the Photo object is an instance of Photo class, method calls are permitted. To make this work you also need a setAlbum() for every Photo created.

Still have questions? Get your answers by asking now.