• Log in or sign up for an account here: https://www.sythe.org/login

[Java] Using a method/variable from a different class

Joined
Dec 4, 2007
Sythe Gold
0
Messages
321
Overview

This is a basic tutorial on how to call a method or variable from a different class. Excuse my conventions as this is being written mostly in the chat text box.​

Requirements:​

  • JDK (Any version).
  • Ability to understand proper English.
  • Understand how to compile/run a java program.

Step One​

Start your class with any name you want, for this tutorial I shall be using the name 'TestClass'. Include a main void as this is your main class.

Code:
/**
 * Class to show how to call a method or variable from a different class.
 *
 * @version 	1.0 08 Nov 2008
 * @author 	Mohsin Baghori
 */

             public class TestClass {

  /**
   * Implementation of public class TestClass
   */

          public static void main(String args[]) {
         }

  /**
   * Main void declaration.
   */


}

Step Two​

Start another class with any name you wish again but this time do not include the main method.

Code:
/**
 * Class with methods we require in main class.
 *
 * @version 	1.0 08 Nov 2008
 * @author 	Mohsin Baghori
 */

             public class MethodClass {
	}

  /**
   * Implementation of public class MethodClass
   */


Step Three​

Now create some random methods or variables inside of your new class, or in my example 'MethodClass.Java'. Make sure the methods or variables are declared as 'public'.

Code:
/**
 * Class with methods we require in main class.
 *
 * @version 	1.0 08 Nov 2008
 * @author 	Mohsin Baghori
 */

	public class MethodClass {

  /**
   * Implementation of public class TestClass
   */

		public int valueX;
		
  /**
   * Declaration of integer valueX, value is unknown.
   */

		public int valueY;

  /**
   * Declaration of integer valueY, value is unknown.
   */

		public int finalValue;

  /**
   * Integer declared to represent the answer of method doTheMath.
   */

		public void doTheMath() {
		valueX = 150;
		valueY = 5;

		finalValue = valueX / valueY;
		System.out.println("The the final value of valueX / valueY is "+finalValue);
		}

  /**
   * Method where integers x and y are each given values then x is divided by y.
   */
		
	}
 
Back
Top