Results 1 to 2 of 2
- 03-21-2008, 04:01 AM #1
Member
- Join Date
- Nov 2007
- Posts
- 13
- Rep Power
- 0
using elements from other classes
I made two classes. Let's say class1 and class2. The class1 has the main method. I am creating a (second) method in class1 and I can take strings, integers etc from my main class e.g.
Java Code:public Class1{ public static void main method (String [] args){ int nameOne=0; String nameFirst=null; secondMethod(one, first); //I 'take' both the int and the String. } public void secondMethod (int nameOne, String nameFirst){ //etc }
Last edited by Camden; 03-21-2008 at 04:06 AM.
- 03-21-2008, 08:25 AM #2
The Java compiler gets upset when it sees the word "class" and gets busy trying to do something with it. So we generally try to avoid using it. When I tried to compile your Class1 the compiler told me this:
Java Code:C:\jexp>javac class1.java class1.java:1: class, interface, or enum expected public Class1 { ^
Java Code:public class FirstClass { public static void main (String[] args) { int nameOne = 57; String nameFirst = "Claude"; // Send these two values off to our two methods. // We are in "static" context (the [i]static[/i] modifier is // in the method declaration of this ("main") method so we can // call the [i]firstMethod[/i] directly because it also has // the [i]static[/i] modifier in its method declaration. firstMethod(nameOne, nameFirst); // The [i]secondMethod[/i] method is not static, ie, its method // declaration does not include the [i]static[/i] modifier. So // we cannot call it directly. So we use an instance variable // of the enclosing class. // Create an instance of FirstClass and save a reference to it // in a local variable called (most anything!) "firstClass". FirstClass firstClass = new FirstClass(); // instance of firstClass // Use this variable, aka reference, to call the non–static // method [i]secondMethod[/i]. firstClass.secondMethod(nameOne, nameFirst); // Trying to call [i]secondMethod[/i] directly causes a compile // error: //secondMethod(nameOne, nameFirst); } private static void firstMethod(int n, String s) { System.out.println("In firstMethod: n = " + n + " s = " + s); } private void secondMethod(int n, String s) { System.out.println("In secondMethod: n = " + n + " s = " + s); } }
Similar Threads
-
Sorting Elements in a TreeMap
By Java Tip in forum java.langReplies: 0Last Post: 04-12-2008, 09:47 PM -
Elements package
By BlitzA in forum New To JavaReplies: 0Last Post: 12-28-2007, 12:58 AM -
deleting elements
By nalinda in forum New To JavaReplies: 2Last Post: 12-06-2007, 02:42 AM -
Help with array of elements
By zoe in forum New To JavaReplies: 1Last Post: 07-24-2007, 06:33 PM
Bookmarks