Using methods from another class in the main? - java

Okay so I did search this question and a decent amount of results showed up. All of them seemed to have pretty different scenarios though and the solutions were different for each one so I'm a bit confused.
Basically, I have a Driver class that runs my program and contains the main method. I have a second class that has a few methods for editing a party (like party of characters in a game). What I wanted to do was this (part of main method)
System.out.println("Are you <ready> for your next battle? Or do you want to <edit> your party?");
Scanner readyScanner = new Scanner(System.in);
String readyString = readyScanner.next();
while(!readyString.equals("ready") && !readyString.equals("edit")) {
System.out.println("Error: Please input <ready> if you are ready for your next battle, or <edit> to change your party.");
readyScanner = new Scanner(System.in);
readyString = readyScanner.next();
}
if(readyString.equals("edit")) {
displayEditParty(playerParty, tempEnemy);
}
A lot of this is just some background code, the problem lies with
displayEditParty(playerParty, tempEnemy);
I get the error
Driver.java:283: cannot find symbol
symbol : method
displayEditParty(java.util.ArrayList<Character>,java.util.ArrayList<Character>)
location: class Driver
displayEditParty(playerParty, tempEnemy);
So, how could I call this method from another class in my main? In my code I use methods from other classes a few times, I'm a bit confused as to this one doesn't work.

You should make displayEditParty function public static and then you can use it in other class by className.displayEditParty(?,?);
Methods of class can be accessible by that class's object only. Check below code:
class A{
void methodA(){
//Some logic
}
public static void methodB(){
//Some logic
}
}
public static void main(String args[]){
A obj = new A();
obj.methodA(); // You can use methodA using Object only.
A.methodB(); // Whereas static method can be accessed by object as well as
obj.methodB(); // class name.
}

If your method is a static, you can call ClassName.methodName(arguments);
If your driver class not a static one you should create an instant of that class and call your method.
ClassName className=new ClassName();
className.displayEditParty(playerParty, tempEnemy);

I dont see where your declaring the Driver class in your code.
Driver foo = new Driver();
foo.displayEditParty(playerParty, tempEnemy);

Related

Can't access functions in another class

****EDIT** For everyone saying call it like
FunctionTestTest.numberCheck(userNumber);
I have tried that numerous times before posting on here it didnt work.
People downvote a question that they cant even answer, great...
On another project Im working on I couldn't call functions from another class. Been trying to fix it all day. Decided to throw up a a few lines of code & try call a function from another class just to make sure i didn't have an unnoticed syntax error in my main project.
can anyone see what the problem is here?
returning this error:
cannot find the symbol
symbol: class FunctionTestTest
location: class FunctionTest
...
public class FunctionTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int userNumber = 0;
System.out.println("Please enter a number between 1 - 10");
userNumber = input.nextInt();
FunctionTestTest ft = new FunctionTestTest();
FunctionTestTest.numberCheck(userNumber);
}
}
and..
public class FunctionTestTest{
public static void main(String[] args){
}
public static void numberCheck(int num){
if (num == 1){
System.out.println("function works");
}
}
}
The error is caused because you are probably using class from another package. In this case you have to import it first before using.
If you are using any IDE there should be a hotkey to fixing your problem.
Also...
You don't need to create an object instance to access static methods of certain class. Simply use:
FunctionTestTest.numberCheck(userNumber);
It is not recommended, but you can call a static method on object instance like:
new FunctionTestTest().numberCheck(userNumber);
here you are calling other class constructor and is not present there:
FunctionTestTest ft = new FunctionTestTest(userNumber);
also check if FunctionTestTest class present is some other package then import it
ft.(userNumber);
Your method invocation is incorrect.
Your probably wanted ft.numberCheck(userNumber) or FunctionTestTest.numberCheck(userNumber). The latter is preferred as you are incoking a static member.
If is it a static method, you just call it as:
ClassName.methodName();
There is no need to instantiate an object to use a static method like what you did.
Example:
public class MyClass{
public static void myMethod(){
//do whatever..
}
}
public class OtherClass{
public static void main(String[] args){
MyClass.myMethod(); //invoke a static method from another class
}
}

Ways of calling non static method from main in Java

We all know that we cannot call a non-static method from Java's static main method directly. I've written 2 ways to call non-static method from main (shown below).
What I wanted to ask is: Is there any significance difference between using code 1 and code 2 to overcome the limitation?
Code 1
public class Demo
{
public static void main(String[] args)
{
Demo demo = new Demo();
demo.printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
Code 2
public class Demo
{
public static void main(String[] args)
{
new Demo().printText();
}
public void printText()
{
System.out.println("Method successfully called.");
}
}
NOTE: In school, our professor told us "In Java, staticmethods of a class can be invoked through the name of the class in which they are defined, without having to instantiate an object of the class first."
But in code 2 no object was instantiated, yet I was able to call the non static-method?
There are 2 main things to be considered while using the first one over the second..
you will still have a reference to the Demo object, so you can call demo.someOtheMethod().
Your demo object will not be ready for Garbage collection as soon as printext() returns. i.e, it will not be ready until you actually exit main(). In the second case, it will be ready as soon as printext() returns..
The only difference is that you can reuse the value in the object demo later. However, you should not create an instance just to call such a method. The correct way to do this is to make the method static.
There is no any difference of executing code or the creating the object.
But in the second method, you don't have a reference to the object you created.(in first method, demo is the reference for the Demoobject) So you can't do any other thing with this object further, as there is no way of referencing it.
as example:
Suppose you had another method inside class Demo called foo1()
in first example you can run both method using a single object.
Demo demo = new Demo();
demo.printText();
demo.foo1();
but in the second method, You have to do it with 2 objects seperately.
new Demo().printText();
new Demo().foo1();
In Code1, you are creating an object using the class name as a reference variable, and calling that function and this would work very finely.
in code2, you are creating an anonymous object, which is basically used whenever we want to use the object only once in the lifecycle of the class.
In both code, the program will work finely.

java class instance

I have a simple Java theory question. If I write a class that contains a main() method along with some other methods, and within that main method invoke an instance of the class (say new Class()), I'm a bit confused why a recursion doesn't occur. Let's say I'm writing a graphing program, where the other methods in the class create a window and plot data; in the main method I call an instance of the class itself, and yet only one window appears. That's great, and it's what I wanted, but intuition suggests that if I create an instance of a class from within itself, some sort of recursion should occur. What prevents this? Here is an example (in my mind, I'm wondering what prevents unwanted recursion):
public class example{
method1(){create Jpane}
method2(){paint Jpane}
method 3(){do some computations}
public static void main(String[] args){
new example(); // or create Jblah(new example());
}
}
I think you're confusing the main method - which is just the entry point of the program - with a constructor.
For example, if you wrote:
public class Example {
public Example() {
new Example(); // Recursive call
}
public static void main(String[] args) {
// Will call the constructor, which will call itself... but main
// won't get called again.
new Example();
}
}
Then that would go bang.
The main method does not get executed automatically when you instance a class. It simply can be used as an entry point to an application - and then will be executed once.
Recursion isn't a bad thing. I suspect you are asking why there isn't an infinite recursion.
The big concept you are missing is that when you call new Example() you are allocating memory and then invoking just one method (the constructor). The main() is only invoked at the start of the whole program unless you explicitly call it.
--- edited to add
public class MyMainClass {
public static void main(String arg[]) {
Calculator c = new Calculator();
int x = c.factorial(5);
}
}
class Calculator {
Calculator() { }
public int factorial(int x) {
if (x > 1) return x * factorial(x - 1);
else return 1; // WARNING: wrong answer for negative input
}
}
Since factorial doesn't use any instance variable, it could have been declared static and called as Calculator.factoral(5); without even using new, but I din't do that since showing off new was the whole point of the example.
just because you have a main method in the class doesn' mean that it will be called every time you create the class.
Java looks for main as an entry point for the program, and calls it upon startup. Any objects you instantiate from their do not call main, since as far as java is concerned, it has done its job of making the entry point to the program.

Is it true that java.lang.Class object is created when the Java class is loaded, even before instantiation takes place?

Suppose the classes has code like this:
class C {
public static void show() {
}
}
class CTest {
public static void main (String[] args) {
C.show();
}
}
Then will it be perfectly legal to conclude that while referring to class C to access the static method show() here, behind the scene Java is actually calling the show() method through Java reflection ?
I.e. is it actually doing something like this
Class test = Class.forName(C);
test.show();
to call static methods?
If not, then how is it actually calling the static methods without creating objects?
If the above explanation is true, then how we'll justify the statement that "static members are only associated with classes, not objects" when we're actually invoking the method through a java.lang.Class object?
The JVM doesn't need to do anything like Class.forName() when calling a static method, because when the class that is calling the method is initialized (or when the method runs the first time, depending on where the static method call is), those other classes are looked up and a reference to the static method code is installed into the pool of data associated with that calling class. But at some point during that initialization, yes, the equivalent of Class.forName() is performed to find the other class.
This is a specious semantic argument. You could just as easily say that this reinforces the standard line that a static method is associated with the class rather than any instance of the class.
The JVM divides the memory it can use into different parts: one part where classes are stored, and one for the objects. (I think there might have been third part, but I am not quite sure about that right now).
Anyways, when an object is created, java looks up the corresponding class (like a blueprint) and creates a copy of it -> voila, we have an object. When a static method is called, the method of the class in the first part of the memory is executed, and not that of an object in the second part. (so there is no need to instantiate an object).
Besides, reflection needs a lot of resources, so using it to call static methods would considerably impact performance.
For extra info:
The called class will get loaded when it's first referenced by calling code.
i.e. The JVM only resolves and loads the class at the specific line of code that it first needs it.
You can verify this by using the JVM arg "-verbose:class" and stepping through with a debugger.
It will call ClassLoader.loadClass(String name) to load the class.
You can put a println statement into the ctor, to verify, whether it is called or not:
class C {
public static void show () {
System.out.println ("static: C.show ();");
}
public C () {
System.out.println ("C.ctor ();");
}
public void view () {
System.out.println ("c.view ();");
}
}
public class CTest
{
public static void main (String args[])
{
System.out.println ("static: ");
C.show ();
System.out.println ("object: ");
C c = new C ();
c.view ();
c.show (); // bad style, should be avoided
}
}

Calling main method class from another java class

I have two java classes.One in which my GUI is written and the other class in which i have implemented an interface(call it class 2).My project starts from the main method of GUI.I want to send a string to my GUI class from the class 2 for displaying it in the Text area but nothing is happening.
As my main gui class is
public class GraphicalInterface extends javax.swing.JFrame{
//I have created a function over here for displaying string in text area
public void show1(String name)
{
jTextArea1.setText(name);
}
//buttons code
public static void main(String args[]) {
//code
}
}
I have created an object of this class in my class 2 like below
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
Please help me out that how can i call main method class from another java class.Thanks.
You may be trying to call this code outside of a constructor or method (or initializer block) and in Java, this can't be done. Instead call this code inside of a method or constructor.
I guess that you have a design problem in your project. Let me expain. You say you have a GUI class "GraphicalInterface" which holds the main method which is the starting point of an application in Java. You say you need to call the main method of this class in another class,
"your class 2". If so why isn't the place belonging to the "main method" of your application in which you try to call this GUI's main method. Call GUI's main method x(), let the place that you call x() belong to the main method.
If you need to operate on the GUI's fields in another classes and also keep the main method still there, then I suggest you to apply Singleton Pattern to your GUI class. In that way you
will be able to refer the only instance of your public singleton class everywhere in your application.
public class GraphicalInterface extends javax.swing.JFrame
{
public String textAreaContent;
public getX()( return textAreaContent;)
public setX(String s)( this.textAreaContent = s;)
public void show1()
{
jTextArea1.setText(this.getTextAreaContent());
}
public static void main(String args[])
{
//code
}
}
From your other class:
GraphicalInterface b=new GraphicalInterface();
b.setX("text area content");
b.show1();
No, the best solution is not to do this, and if you feel you must, it is likely because your design is somehow broken. Instead write your code so that your classes are true OOPs classes that interact in an intelligent way (low coupling, high cohesion), and to only need one main method.
Also, you state:
GraphicalInterface b=new GraphicalInterface();
b.show1("pear");// it does not allow me to write this statement
What do you mean by "it does not allow me to write this statement"? Does the Java compiler give a compilation error? Does the JVM throw an exception? Does the JVM reach out of your monitor and slap you in the face? Please let us know all the details necessary to be able to help you.
You need to create a method in class2 and call it from your main method.
Sample code class1
public class Test1 {
public void show(String ab){
System.out.println(ab);
}
public static void main(String[] args) {
Test2.Test2();
}
}
Above code i create a class Test1.java like your class1 and create a method with one parameter and call it from class2 method.
Sample code class2
public class Test2 {
static void Test2(){
new Test1().show("Pass String to class1 show method");
}
}
here you can pass your string value.

Categories