Refresher on Java classes in separate files
Posted
by
JohnFaig
on Stack Overflow
See other posts from Stack Overflow
or by JohnFaig
Published on 2012-12-04T16:53:14Z
Indexed on
2012/12/04
17:04 UTC
Read the original article
Hit count: 279
I need a refresher on moving classes from one file into two files. My sample code is in one file called "external_class_file_main". The program runs fine and the code is shown below:
Public class external_class_file_main {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
I move the get_a_random_number class to a separate file called "external_class_file". When I do this, I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method get_a_random_number(int, int) is undefined for the type
external_class_file_main
at external_class_file_main.main(external_class_file_main.java:20)
The "external_class_file_main" now contains:
public class external_class_file_main {
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
The "external_class_file" now contains:
public class external_class_file {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
}
© Stack Overflow or respective owner