I have global variables in Question class and increments these values in event handler. I have another class User which contains a static method Details(). I want to pass these two variables values (after increments) from event handler to the Details() of the User class.:
public class Question {
public int phCounter = 0;
public int chemCounter = 0;
private void CategoryCbActionPerformed(java.awt.event.ActionEvent evt) {
phCounter++;
chemCounter++;
}
}
...
public class User {
static void Details() {
public counter ;
}
}
My question is is there any way, except to send values as arguments to Details(), in which I can inject these incremented values inside Details() method.
First off: Method names in Java are camelCase. Not UpperCase ;)
If you want to access fields of a class in another class there are serveral ways to achieve that. The easiest one are static fields:
public class MyClass {
public static String accessible;
}
public class AnotherClass {
public void someMethod() {
// You can set the value ...
MyClass.accessible = "New value";
}
public void anotherMethod() {
// ... and get the value.
System.out.println(MyClass.accessible);
}
}
But remember: The value of a static field will be always the same unless you change it, even when you create new instances of the class where the static field is used. You should avoid static fields if possible. In most cases you can take the OOP way to achieve the same result.
~ Morph
I can inject these incremented values inside Details() method.
what does this statement mean?
your code below can not be compiled!
public class User{
static void Details()
{
public counter;
}
}
if you want to use reflection to send args to method ,why not just call User.Details(int a,int b)
Related
Is it possible to access an object created in one class from another class without using parameters/arguments?
For example:
public class Main {
public static void main(String[] args) {
Two make = new Two(); // Object I created.
make.ham();
}
}
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three {
public static void accessObject() {
// Can I access the object make here without parameters?
}
}
What I understood is that you want to access to make object, created inside Main class (Two make = new Two());. And yes, it's possible to do it.
You have to create your variable make as global and static (and it's recommended be public or protected, in case you have your classes in separate files).
So, inside your Main class, you will have to do something like:
public class Main {
public static Two make;
public static void main(String[] args) {
make = new Two(); // Object I created.
make.ham();
Three.accessObject();
}
}
As you can see, I created the make variable as static and global. This is necessary because your main method is static, and it's global to be able to be recognized by other classes. And to can call to accessObject method, I did it with the class name (because that method is static)(Three.accessObject();)
And finally inside your Three class, in the accessObject method it's necessary call to the static variable make from Main class:
class Three {
public static void accessObject() {
System.out.println("using make object from Main class in Three class...");
Main.make.ham();
}
}
As you can see now, I called the variable make with the name class Main because it's static, and finally, you will be able to call the ham method by this way.
You could you inheritance to solve your problem. For example, you would write:
class Three extends Two {
public static void accessObject() {
// You can now access the "Two" object since you have now made
// Three a subclass of Two.
}
}
EDIT:
If you wanted to say, change the implementation of the ham() method, you could do something like this:
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three extends Two {
#Override
public void ham() {
System.out.println("I'm inside ham, but inside the Three class.);
}
}
Say I have a class with some mutable fields:
public class Test
{
private boolean isCorrect;
private String userId;
public void run() {...}
// more methods
}
The run() method will be modifying these fields. My issues is that the caller of this class might call run() any number of times, and for this reason I should be re-setting the fields back to null.
My question is, what is the best practice for this scenario? Should I reset the fields every time the method is called?
public void run()
{
isCorrect = null;
userId = null;
// do stuff
}
Or is there a cleaner/smarter approach to this?
The simple answer is use local variables. The OP has clarified in the comments that run calls other methods on the same instance that expect to use these variable too.
The class should be split. The run method should create an object containing the fields and call methods on that.
public class Test {
public void run() {
TestImpl impl = new TestImpl();
impl.run();
}
// more methods
}
class TestImpl {
private boolean isCorrect;
private String userId;
public void run() {...}
// more methods
}
You could make the new class a nested class, though that does cause excessive indention. An inner class would also have direct access to any longer lived variables of Test. An anonymous inner class (or, more obscurely, a local class) would be even more convenient but indented.
I would do it this way. Using an exception. So anyone who dares to use run() twice gets kicked out.
package test;
import com.sun.jdi.IncompatibleThreadStateException;
public class Test{
private boolean isRunning = false;
public void run() throws IncompatibleThreadStateException{
if(this.isRunning) {
throw new IncompatibleThreadStateException();
}
else {
this.isRunning = true;
}
}
public static void main(String[] args) {
}
}
For example I have a MovieDatabase class that contains a list of Movie objects. In my main code, I initialize all the objects in the MovieDatabase. However I wish to call this MovieDatabase in another class to access the library. How would I do this?
Do I add in get methods in my main code and return it? Or is there another way (eg. changing the list of objects to protected/public?)
Thanks!
Code's supposed to be 3 seperate classes, Main, MovieDatabase & Movie.
An instance of movieDatabase is initialized in Main. Upon construction, it calls loadMovieList() and populates the list from a text file. However I wish to call the same instantiation of movieDatabase from another class in order to access the movies, so that I do not have to repeat the loading.
public class Main {
public static void main(String[] args) {
MovieDatabase movieDatabase = new MovieDatabase();
}
public class MovieDatabase {
ArrayList<Movie>movieList = new ArrayList<Movie>();
String fileAddress = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/MovieDatabase/movieDatabase.txt";
public MovieDatabase()
{
numOfMovie=0;
loadMovieList();
}
public int getNumOfMovie() {
return numOfMovie;
}
public void addMovieToList(Movie movie) {
movieList.add(movie);
numOfMovie++;
}
public Movie selMovieByID(int movieID) {
int index=-1;
for (Movie m : movieList) {
index++;
if (m.getMovieID() == movieID)
break;
}
return selMovieByIndex(index);
}
public Movie selMovieByIndex(int index) {
return movieList.get(index);
}
public void loadMovieList()
{
//loads through text file
addMovieToList(new Movie(tempMovie));
System.out.println("Movie Database loaded");
}
public class Movie{
private int movieID;
private String movieName;
private int movieDuration; //in minutes;
private String movieRating; //G; PG; PG13; NC16; M18; R21;
private boolean has3D;
private boolean status;
}
If you have a class that depends on a NameLibrary, you should inject it via the constructor or a set method.
Firstly, its difficult to assess what issues you truly have without any code to show us.
However you mention main method, as in
public static void main(String args[]){};
this main method is designed specifically to run the application, your compiler needs that specific method, it is not designed to be used as an accessor method
e.g.
public int getValue(){
return value;}
this is not the only reason you can't access the main method variable. main doesn't have a return type (due to the use of void) plus the idea of SCOPE (each method has a scope, any method that contains a variable can see that variable, but nothing outside of it can directly see it without a return type) you use scope to limit what can be accessed or what cannot be accessed outside of the methods or classes (thats why class variables usually will have private, in order to limit accessibility)
Create a getter-method which returns the list inside your NameLibrary. if your other class extends from NameLibrary you can call this getter-method with the object reference to your NameLibrary class.
If you want int x to be accessible from other classes, you write:
public class myClass{
public int x = 0;
}
To access it from other classes, you simply write:
myClass.x ... (do something)
I've got this int variable inside the class StringSplit whose value I need to pass to another class called EndStatement to print out; can't really pass it as a parameter though I think. How can I best get the variable to where I need it? Can someone help with a hint? I've read the Java tutorials but don't quite get them. Variables and passing them around seem to be one of my Achilles' heels in Java programming.
EDIT TO ADD: parseCommands can call several different Statement classes e.g. EndStatement or PrintlnStatement depending on the first element of an Array parsed from a String which serves as a keyword to a HashMap called commandHash. The Statement classes implement the Directive interface which only has a method called execute with the parameterString[] parts. (EndStatement implements Directive). Expanded the parseCommands method to show what's going on.
public class StringSplit
{
public void parseCommands(String fileName)
{
//FileReader and BufferedReader to read a file with the code
//to execute line by line into an ArrayList myString
int lineCounter=0; //need to get this variable's value into class EndStatement
for (String listString: myString)
{
lineCounter++;
String[] parts=listString.trim.split("[\\s]+", 2)//split String into 2 parts
//to get commands
Directive directive= commandHash.get(parts[0])//parts[0] is the hashmap keyword
}
public class EndStatement implements Directive
{
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(lineCounter +"lines processed.");
}
public static void main (String[]args)
StringSplit ss = new StringSplit();
ss.parseCommands(args[0]);
}
This is my first time answering a question but I think I'm right.
In StringSplit you want to declare linceCounter in a data field.
public class StringSplit
{
public void parseCommands(String fileName)
{
lineCounter=0; //this is the variable I need to pass into a different class
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter()
{
return lineCounter;
}
private int lineCounter; //this is what I call a data field, you should declare these as private as oppose to public to comply with encapsulation
}
Then in your main method call getLinceCounter, then pass what it returns to EndStatment.
Does this make sense? Did I understand your question right?
public class StringSplit
{
private int lineCounter=0;
public void parseCommands(String fileName)
{
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter() {
return lineCounter;
}
}
public class EndStatement implements Directive
{
StringSplit ss = new StringSplit();
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(ss.getLineCounter() +"lines processed.");
}
public static void main (String[]args)
{
ss.parseCommands(args[0]);
}
}
I think you mix some terms. There is no such thing as passing variables from one class to another. I assume that what you want to do is simply be able to access (set/get) your variable outside StringSplit class. In order to do that you must declare lineCounter outside parseCommands method as StringSplit's property. Currently lineCounter is local to parseCommands method and as such cannot be visible/accessed outside that method not mentioning to be able to access it from outside a class/object. Do that:
public class StringSplit
{
public int lineCounter = 0;
...
Now you'll be able to access lineCounter from different methods of the same class and from methods outside your class. Making lineCounter public gives others full access to it. As 'Jon' has pointed out it may be dangerous sometimes but for this example case is acceptable. You may see how writing from outside can be prevented using 'Nurlan's' private field with member used to provide read acces only.
Right now I have two .java files.
The Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
and the NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
This is of course very simplified, but is there any way I can accomplish this?
As many have answered, the correct method is to pass the value in to the constructor of the new class.
If for some reason you cannot do that, then you can use a public static accessor method in Main to access the value (this would be slightly better than just making the field public).
E.g.
public class Main
{
private static int integer = 15;
public static int getInteger()
{
return integer;
}
}
public class NeedInteger
{
public NeedInteger()
{
int integer = Main.getInteger();
}
}
Add a constructor to NeedInteger (and optionally a member if you need to also store it):
public class NeedInteger {
private int integer;
public NeedInteger(int integer) {
this.integer = integer;
System.out.println(integer);
}
}
Then pass your value when you create the instance:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger(integer);
}
You would have to do some bad juju moves (like using a global variable) or pass it to the constructor.
NOTE: your
public class NeedInteger {
System.out.println(integer);
}
has no method in it. I would recommend all this to be rewritten as such:
public Class NeedInteger {
NeedInteger(int integer) {
System.out.println(integer);
}
}
If you really want the work to be done on construction.
EDIT: From your comment above.
Instead, have the class structured so:
public Class NeedStringArray {
NeedStringArray(String[][][] stringArr) {
//work with String array here
}
}
That has no real additional overhead, since the actual array will not be passed, but only a reference to it. You WILL likely want to set the array to be final or something, to avoid it being edited in the NeedStringArray constructors.
integer is private, so it cannot be accessed by NeedInteger. you'll have to make it public or use a setter or getter and you'll need to use Main.integer since it's static.
Generally, you set in the Constructor.
Pass in the variable to the class constructor.
An array reference would be just that--a reference.
Or you could pass in the class itself, or use a static (meh).
Per your comment I'd say you can either host your array in a singleton
or as others suggested have the second class accept the reference to the array in the constructor. You can then use Dependency Injection framework (e.g. Guice) to get wire them up