I do have one class that has one instance variable, that is being injected like below:
public Class HierarchyAccessor {
#Inject
HierarchyProvider provider;
public int GetAllHierarchies(HierarchyAccessorInput input) {
String requiredVariable = input.getId;
provider.provideHierarchy(requiredVariable);
}
}
Here, I do have another class HierarchyHelper, that has one static function which is performing some operation by creating an object of class HierarchyAccessor.
public Class HierarchyHelper {
public static List<String> getHierarchies() {
// Here I want to create the object of HierarchyAccessor.
// this is not working .
HierarchyAccessor accessor = new HierarchyAccessor();
/*
It performs some operations and returns the required output.
*/
}
}
So, here I'm unable to create the object of HierarchyAccessor class inside the static method, due to some constraint, I can't change this static method to non-static.
Can someone please suggest how to create the object of HierarchyAccessor inside the static method?
so I've been wracking my brains over why this isn't working for an hour now. I have two classes, class One containing an ArrayList of ArrayLists and a method to add another element to that list, and class Two, from which I'm trying to access that method.
public class One
{
private ArrayList<Element> myarraylist;
public One()
{
myarraylist = new ArrayList<Element>();
}
public void addElement(String name)
{
myarraylist.add(new Element(name));
}
}
//Element being another class
public class Two
{
One database;
public static void main(String[] args)
{
Two two = new Two();
two.startMenu();
}
public Two()
{
One database = new One();
}
public void addElem()
{
Scanner keyboard = new Scanner(System.in);
String name = keyboard.next();
database.addElement(name);
}
}
//where startMenu is just a small multiple choice menu thingy
Problem is, when I try to run through it and I get to the last line, I get the message: java.lang.NullPointerException
I tried inspecting the objects (I use BlueJ), and the ArrayList is initialized when I just make an instance of class One, but when I make an instance of class Two, the database instance is null.
Thanks in advance for your answers :D
The problem is at the following lines
public class Two
{
One database;
public Two()
{
One database = new One();
//this variable is not the same as the one declared outside the constructor
}
When declaring a variable in a method which has the same name as the variable declared in the class, the modifications which happen on the variable declared inside the method will not be seen in the variable outside the method(because the 2 variables are different). The variable in the method is shadowing the variable from the class.
To differentiate between the two variables you must use the this keyword
this.database = new One();
The final solution should be
public class Two
{
One database;
public Two()
{
this.database = new One();
}
The reason you get the NullPointerException when doing database.addElement(name); is because in your example the database is not instatiated beacause the object created is stored in a different variable named database and not the one declared as a class attribute.
I've seen this question asked in several ways, but the code is usually specific to the user, and I get lost a little. If I'm missing a nice clear and simple explanation, I'm sorry! I just need to understand this concept, and I've gotten lost on the repeats that I've seen. So I've simplified my own problem as much as I possibly can, to get at the root of the issue.
The goal is to have a main class that I ask for variables, and then have those user-inputted variables assessed by a method in a separate class, with a message returned depending on what the variables are.
import java.io.*;
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess();
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
And the method I'm trying to use is:
public class Assess extends MainClass {
public static void main(String[] args) {
String A = MainClass.A;
String B = MainClass.B;
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) | (B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
}
else {
System.out.println ("Failure");
}
}
}
I recognize that I'm not properly asking for the output, but I can't even get there and figure out what the heck I'm doing there until I get the thing to compile at all, and I can't do THAT until I figure out how to properly pass values between classes. I know there's fancy ways of doing it, such as with arrays. I'm looking for the conceptually simplest way of sending a variable inputted from inside one class to another class; I need to understand the basic concept here, and I know this is super elementary but I'm just being dumb, and reading what might be duplicate questions hasn't helped.
I know how to do it if the variable is static and declared globally at the beginning, but not how to send it from within the subclass (I know it's impossible to send directly from the subclass...right? I have to set it somehow, and then pull that set value into the other class).
In order to pass variables to an object you have either two options
Constructor - will pass parameter when creating the object
Mutator method - will pass parameters when you call the method
For example in your Main class:
Assess assess = new Assess(A, B);
Or:
Assess assess = new Assess();
assess.setA(A);
assess.setB(B);
In your Assess class you have to add a constructor method
public Assess(String A, String B)
Or setter methods
public void setA(String A)
public void setB(String B)
Also, Assess class should not extend the main class and contain a static main method, it has nothing to do with the main class.
Below there is a code example!
Assess.java
public class Assess {
private a;
private b;
public Assess(String a, String b) {
this.a = a;
this.b = b;
}
public boolean check() {
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) ||
(B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
return true;
} else {
System.out.println ("Failure");
return false;
}
MainClass .java
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess(A, B);
boolean isBothPresent = test.check();
// ................
} catch (IOException e){
System.out.println("Error reading from user");
}
}
I think what you're looking for are method parameters.
In a method definition, you define the method name and the parameters it takes. If you have a method assess that takes a string and returns an integer, for example, you would write:
public int assess(String valueToAssess)
and follow it with code to do whatever you wanted with valueToAssess to determine what integer you wanted to return. When you had decided that i was the int to return, you would put the statement
return i;
into the method; that terminates the method and returns that value to the caller.
The caller obtains the string to be assesed, then calls the method and passes in that string. So it's more of a push than a pull, if you see what I mean.
...
String a = reader.readLine();
int answer = assess(a);
System.out.println("I've decided the answer is " + answer);
Is that what you're looking for?
A subclass will have access to the public members of the superclass. If you want to access a member using {class}.{member} (i.e. MainClass.A) it needs to be statically declared outside of a method.
public class MainClass {
public static String A;
public static String B;
...
}
public class Subclass {
public static void main(String[] args) {
// You can access MainClass.A and MainClass.B here
}
}
Likely a better option is to create a class that has these two Strings as objects that can be manipulated then passed in to the Assess class
public class MainClass {
public String A;
public String B;
public static void main(String[] args) {
// Manipulate A, B, assign values, etc.
Assess assessObject = new Assess(A, B);
if (assessObject.isValidInput()) {
System.out.println("Success!");
} else {
System.out.println("Success!");
}
}
}
public class Assess {
String response1;
String response2;
public Assess (String A, String B) {
response1 = A;
response2 = B;
}
public boolean isValidInput() {
// Put your success/fail logic here
return (response1.compareToIgnoreCase("yes") == 0);
}
}
First you don't need inheritance. Have one class your main class contain main take the main out of Assess class. Create a constructor or setter methods to set the variables in the Assess class.
For instance.
public class MainClass
{
public static void main(String[] Args)
{
Assess ns = new Assess( );
ns.setterMethod(variable to set);
}
}
I'm not 100% sure of your problem, but it sounds like you just need to access variables that exist in one class from a subclass. There are several ways...
You can make them public static variables and reference them as you show in your Assess class. However, they are in the wrong location in MainClass use
public static String A, B;
You can make those variables either public or protected in the parent class (MainClass in your example). Public is NOT recommended as you would not know who or what modified them. You would reference these from the sub-class as if present in the sub-class.
public String A, B; // Bad practice, who modified these?
protected String A, B;
The method that might elicit the least debate is to make them private members and use "accessors" (getters and setters). This makes them accessible programmatically which lets you set breakpoints to catch the culprit that is modifying them, and also let you implement many patterns, such as observer, etc., so that modification of these can invoke services as needed. If "A" were the path to a log file, changing its value could also cause the old log to close and the new one to be opened - just by changing the name of the file.
private String A, B;
public setA(String newValue) {
A = newValue;
}
public String getA() {
return A;
}
BUT ...
Your question says "send to the subclass", but confounded by your knowing how to do this using global variables. I would say that the simplest way is to provide the values with the constructor, effectively injecting the values.
There are other ways, however, your example shows the assessment performed by the constructor. If your Assess class had a separate method to perform the assessment, you would just call that with the variables as arguments.
Your example is confusing since both classes have main methods and the child class does the assessing - I would think you would want the opposite - Have MainClass extend Assess, making "MainClass an Assess'or", let main assign the Strings to Assess' values (or pass them as arguments) to the parent class' "assess" method ("super" added for clarity):
super.setA(local_a);
super.setB(local_b);
super.assess();
or
super.assess(A, B);
When I am trying to create an object with self reference in constructor I am getting StackOverflowError.
public class Example1 {
private int i;
private Example1 zero;
public Example1(int i) {
super();
if (i > 0) {
this.i = i;
} else {
this.i = this.zero.i;
}
this.zero = new Example1(i);
}
public int getI() {
return i;
}
But when I do with static reference no error occurs.
public class Example2 {
private int i;
private static final Example2 ZERO = new Example2(0);
public Example2() {
this(ZERO.i);
}
public Example2(int i) {
super();
this.i = i;
}
public int getI() {
return i;
}
Since static object will be initialized while loading the class it is working that I am able to understand.
But what is happening during object creation, Can anyone explain in detail?
Exampel1 creates new instances recursively in the constructor.
The static field will only be created once. That's why example 1 created the overflow and the second does not.
Static modifier implies that whatever you made static is shared among all the objects of that class. Since I believe you want to make something like a "default object" inside each Example1 object, the best way to do it is to make it static. This way, you can create as many Example1 objects as you want (or your memory allows) but every one of them will share the static Example1 zero object.
Non static object here is impossible, because it will otherwise try to create another Example1 object inside the Example1 object you just created, which will of course have another Example1 object in an infinite loop, as other people has already stated.
I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.