Using a instance of a method - java

I was wondering if someone could help explain how to call a instance of a class.
For example originally I had a file called "Driver"
Then it has a main method that has all the instances needed for a file to run.
Then in that main file it access another file called with a "Games".
So when I run the program "Driver" which has the following code:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
GameRunner roul = new GameRunner ();
}
}
Then to call an instance of that other file I have something like. Also to make the code work I should have the main method like:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner roul = new GameRunner ();
}
}
Then my other file has something like:
import java.util.*;
class GameRunner
{
public static void roul(Scanner in, int number, int userChoice)
{
Guessing this is still wrong because the driver class should only have :
GameRunner roul = new GameRunner ();
I know it's kinda hard to explain what I'm asking. I hope someone understands.
Thanks.

I strongly recommend reading this (official) tutorial from the people who made Java: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
(No, seriously. Read that tutorial. I linked to the section specifically on object-oriented programming, which explains what you are asking about. It's very useful).
Now to answer your question more directly.
Your roul method is a "class method" (rather than an "instance method") because it has the keyword static in front of its definition. This means that you invoke it using the name of the class, rather than by using a specific object (instance) that you created.
So in order to call the roul method of GameRunner, do the following in your main:
GameRunner.roul(in, number, userChoice);
It is not necessary to instantiate GameRunner unless it has a non-static method that you need to invoke. So unless that's the case, don't do the following:
GameRunner roul = new GameRunner ();
Finally, note that the names of your arguments do not have to be the same as the names of your parameters, as long as their types are the same. The "parameters" are the variables you used when you defined the method. The "arguments" the actual variables you pass to the method.
For example, a method definition has parameters:
public static void myMethod(int parameter1, int parameter2) {
/* do stuff */
}
Whereas a method invocation has arguments that can have a different name:
MyClass.myMethod(number1, number2);

public class Driver {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner runner = new GameRunner ();
// The following line will invoke the target method of your game runner instance.
runner.roul(in, number, userChoice);
}
}

Declare the class and method static then call like this:
GameRunner.roul(); // pass in arguments if needed

public static void run() is the entry point into your application you don't need another one. it looks like you need to brush up on Object Oriented basics.
if you're trying to make a game perhaps you could start with a tutorial? i would suggest using a game library like Lightweight Java Game Library. go ahead and google for some tutorials.

Related

A class with no modifier (default) cannot access a subclass declared as public? Java

I was just doing practice on Hackerrank since I'm still pretty new to Java (I'm only experienced with C and C++, with minimal Python/Matlab/C#). Basically we only had to write the "Checker class" below from scratch. However, I noticed that when I add public to the Checker class it results in runtime error. Does anyone know why? I couldn't find any answers on this online.
Also, yes, I know access modifiers restrictions on how much they can have access to the scope of classes, but it does not make sense to me on how a default class cannot access a public class's method. I'm assuming it is perhaps I'm implementing a parent class that's causing the problem? Here is the RE message I receive on Hackerrank:
Error: Main method not found in class Checker, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
If interested, link to the practice problem for reference: https://www.hackerrank.com/challenges/java-comparator/problem
import java.util.*;
// Write your Checker class here
class Checker implements Comparator<Player>{ //If I add "public" in front I get RE
#Override
public int compare(Player A, Player B){
if(A.score == B.score)
return A.name.compareTo(B.name);
else
return B.score - A.score;
// return A.compareTo(B);
}
}
class Player{
String name;
int score;
Player(String name, int score){
this.name = name;
this.score = score;
}
}
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Player[] player = new Player[n];
Checker checker = new Checker();
for(int i = 0; i < n; i++){
player[i] = new Player(scan.next(), scan.nextInt());
}
scan.close();
Arrays.sort(player, checker);
for(int i = 0; i < player.length; i++){
System.out.printf("%s %s\n", player[i].name, player[i].score);
}
}
}
Interesting question but I've never used this in my whole career.
If there is no public class in the source file then main method can
lie in any class and we can give any name to the source file.
Source: https://dzone.com/articles/why-single-java-source-file-can-not-have-more-than
Because of the remark of #Andy Turner, I tested it a little bit further and indeed you can have a main method in other classes (other than the public one). It all depends on how you call it:
package sample;
class Problem {
public static void main(String[] args) {
System.out.println("main of Problem");
}
}
public class Solution {
public static void main(String[] args) {
System.out.println("main of Solution");
}
}
The source file name must be Solution.java as this is the public class but you can call both main methods:
> java sample.Solution
main of Solution
> java sample.Problem
main of Problem
You can still call sample.Problem when you remove the main method from Solution.
While it's against "customs", it is possible to do what you tried. However the main() method is present in the Solution class, so that's the one you have to run.
From command line you can do that easily:
javac Checker.java
java Solution
as Solution.class will be generated properly.
However if you use an IDE, which you are not very familiar with, you may encounter difficulties when trying to tell them to run a different .class file from the .java they have just compiled. In short: name the file as Solution.java.

Why am I being forced to change methods and varibles to static when calling them from my main method? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}

Access one class's members after running it from another class

I recently wrote a class that implements the run method and then parses a video file while grabbing meaningful information. Now I've created a new class that performs a similar operation on the same file but uses a different method of parsing while grabbing other meaningful information. Long story short, I'm required to use two different methods of parsing because some data cannot be extracted by one and some cannot be extracted by the other. The problem I'm facing is that both classes implement the run method, but now I need to start the new class, grab information, start the other class, grab information, then compare the information and print it to the console. This is the gist of what I'm trying to do:
public class first {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new first().run(args); // <------ A
}
}
public class second {
[public member variables]
....
public void run(String[] args) {
// parse the file from args and store data
}
public static void main(String[] args) {
new second().run(args);
}
}
What I'm trying to do is call the first class's main method in order to keep a reference to the class and grab the data from it when it's finished. So I added something like this in the second class:
public class second {
[public member variables]
first firstClass;
int dataFromFirst = 0;
....
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.main(args); // <------ B
dataFromFirst = firstClass.getSomeData(); // <------ C
}
public static void main(String[] args) {
new second().run(args);
}
}
When I start the second class, everything runs fine, the parser does it's job with both the second and first classes, but when I try to extract the data found by the first class, it's null. I figure once the first class's main method finishes after 'B', once 'A' goes out of scope, everything from the first class is lost. So when I try to get data at 'C', there's nothing there. If this is the case, is there any way I can access the first class's data before it's lost?
I don't have as much knowledge about multithreaded programs so this may just be a very simple solution that I've never seen before.
The reason this doesn't work is that each main method creates its own instance of the class and uses it locally. This has nothing to do with threads, and in fact as far as I can tell your program doesn't actually use multithreading at all.
To fix it, don't call from one main method to the other. In fact, don't even have two main methods in the first place, there's almost never a reason to have more than one. Instead, simply call run directly, like this:
public void run(String[] args) {
// parse the file from args and store data
firstClass = new first();
firstClass.run(args);
dataFromFirst = firstClass.getSomeData();
}

How is it possible to create object in Class definition itself?

I have some doubt on how this works, consider a simple Java program:
package com.example;
public class Test {
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
public void print() {
System.out.println("This is demo");
}
}
This is pretty straightforward program.
However, I have doubt at (1). We are creating an instance of Test, but this is still in the definition of Class Test. How is this possible?
Any explanation to help this would be great.
The instance will be created at run-time.
By then, compile-time is over and all of the code of your application (including all class definition) will be "ready".
Even if you call a constructor of a class that has not been encountered by the JVM up to that point, it will dynamically load the class (in its entirety) before executing the constructor call. Note that a) this might actually fail at run-time, in which case you get a ClassNotFoundError, and b) that cannot happen in your case, because you are calling the constructor of the class from itself (so it must have been loaded already).
The compiler does not run any of your code (not even things like static initializers) during compilation.
But it does make sure (during compilation) that every method or constructor that you are trying to call does in fact exist. Again, this could theoretically fail at runtime (if you mess up class files), in which case you would get a NoSuchMethodError.
First We have to Compile this Porgram using javac After Compilation It will give a Class File.
Now time to Execute Your Class Using java which Invokes JVM and load the Class File to the Class Loader.
java fileName.Class
And here
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
All we know static Content (either it is Variable or Method In Java) Of class loaded when ClassLoader loads a Class
As You see Main Method is a static Method. and So, It will Automatically Load into the ClassLoader with class File.
Now JVM First find the public static void main(String... args) in class. Which is a static Content means Its a part of Class but not a part of Class Instance. There is no need of Class Instance to Invoke this MainMethod`.
main(String... args) will be Invoked without getting Instance of the Class. In that Main Method , Your Class is Getting Instantiated
Test t = new Test(); \\here t is reference Variable to Test Class Object.
Now Because Class is loaded into the class Loader new Test(); will create a New Object in Heap memory Area of JVM and your method
public void print() {
System.out.println("This is demo");
}
will be invoked using t.print() Which is a Instance Method (Not Static), So It needs Class Instance to Invoke print() Method.
Q: Test t = new Test(); (1) <---- How is this possible
A: Because of the "static" in public static void main(String[] args)
The "static" means that method "main()" is independent of any specific class object.
You can create any class object you want - including a new "Test" object.
One of the benefits of defining "main" to be static is that you can use "main()" as a test method for the class. Each class can have it's own "main", and you can test each class individually by specifying that class in your Java command line.
For example:
public class MyClass {
public int add2(int n) {
return n + 2;
}
public static void main (String[] args) {
MyClass unitTest = new MyClass ();
System.out.println ("add2(2)=" + unitTest.add2(2));
System.out.println("Expected result=4");
}
}
Then test as follows:
javac MyClass.java
java MyClass
add2(2)=4
Expected result=4
This question has actually been asked and answered many times. For example:
Why is the Java main method static?
==================================================================
Here are a few more examples that illustrate the point:
public class CreateMyself {
private int value = 0;
private static CreateMyself m_singleton = null;
// EXAMPLE 1: You can legally create an instance in the constructor ...
public CreateMyself () {
value++;
// CreateMyself o = new CreateMyself (); // BAD!!! This will cause infinite recursion and crash your stack!!!
System.out.println ("Leaving constructor, value=" + value + "...");
}
// EXAMPLE 2: You can legally create another instance in a normal class member
public void createAnother() {
// But ... WHY??? Is there anything you can't do directly, in your own instance?
CreateMyself newInstance = new CreateMyself ();
System.out.println ("Leaving createAnother, value=" + value + "...");
}
// EXAMPLE 3: This is a common idiom for creating a "singleton"
// NOTE: for this to work, you'd also make the constructor PRIVATE (or protected), so the client *must* call "getInstance()", instead of "new".
public static CreateMyself getInstance () {
if (m_singleton == null) {
m_singleton = new CreateMyself ();
}
System.out.println ("returning singleton instance...");
return m_singleton;
}
// EXAMPLE 4: Creating an instance in "static main()" is a common idiom
public static void main (String[] args) {
CreateMyself newInstance = new CreateMyself ();
newInstance.createAnother ();
}
}
There are many other possible uses. For example, maybe you'll have a static method that does a database lookup and returns a list matching objects.
Note that most of the cases where it's really useful for a class to have a method where it creates an instance of itself are probably static methods.

How to give a programmatic support to a class with a main

I'm sorry for the title but I can't really find another way to express it. I need to create a class with a double function, if you give to it a file as input from the console or terminal it gives back a print of it's calculations, but the class can be also used as subroutine and give a file to another class for further calculation.
To implement the first task I must define a main to accept input from console like this
java MyClass myfile.file
But then I can not simply get an instance the class inside something else like this
MyClass myClass = new MyClass(file);
cause I will always get an error from the main(IndexOutOfBound since args it's just an empty array).
How can I fix this? I must use the same class to do so, I can not build another class for the subroutine function.
Something like:
public class MyClass {
public MyClass(String nameOfFile) {
...
}
public void doSomething() {
}
public static void main(String[] args) {
MyClass myClass = new MyClass(args[0]);
myClass.doSomething();
}
}
So your main method simply interprets the incoming arguments (as file names or similar), then instantiates and executes your class as another library might.

Categories

Resources