4

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).

1
  • These variables should be getting passed into Assess's constructor. Commented Oct 4, 2016 at 19:48

5 Answers 5

4

In order to pass variables to an object you have either two options

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");
      }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I figured it out. I needed to get rid of the whole public static void and declarations, and replace them ALL with the constructor method. Putting it in any other way confuses the compiler. And me!
Well, that is another solution, you may want to edit your question with the solution you state
that's what your solution is, I just needed to realize it!
1

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?

1 Comment

No, I just didn't understand how the constructor replaces other lines I had. Because I am duuuuumb. But thank you!
1

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);
    }
}

Comments

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); } }

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.