Reputation: 213
So for example I have 2 classes and one interface.
public class mainClass {
private String word;
}
public interface intWord {
public String getOutput();
public void setInput( String input );
public void setLevel ( int level );
}
public class secondClass implements intWord {
//class I want to be able to access 'word' from mainClass without extending it.
public String getOutput() {
}
public void setInput( String input ) {
}
public void setLevel ( int level ) {
}
}
How do I go about accessing "word" in my secondClass without extending mainClass to it? I believe I can add some helper methods somewhere to make it easy....but I can't figure it out!
Upvotes: 0
Views: 87
Reputation: 769
One way to do assuming you want to use "word" as parameter for your setInput method will be to have an instance of mainClass and a getter to access the field word. Here is what it will look like:
public static void main( String args[])
{
// Assuming word is not null
secondClass second_class = new secondClass ();
secondclass.setInput(mainClass.getWord());
}
The other way will be to have your field word be sa static variable and return it with a static getter(Not recommended). Here is what you mainClass should look like:
public class mainClass {
private static String word;
public static String getWord(){
return word;
}
}
And here is how you will access it:
public static void main( String args[])
{
mainClass mainclass = new mainClass();
// Assuming word is not null
secondClass second = new secondClass ();
secondclass.setInput(mainClass.getWord());
}
Upvotes: 1
Reputation: 525
The best way is to create setters and getters for private String word;
in mainClass
and create an object of mainClass in secondClass
and access the getters and setters to get/set the value of word
.
Another thing, if you know that word
is global variable then you can create it as public string word;
instead of private and extend
mainClass in secondClass so as to access it directly.
Just for your knowledge java follows convention where class name should start with capital letter and then follow camel case.
Upvotes: 0
Reputation: 3799
In your mainClass you can add a "getter" method, as seen below
public class mainClass {
private String word;
public String getWord(){
return word;
}
}
And just call getWord() from your second class
You can also dynamically set your word value from your second class by adding a setter method:
public void setWord(String newWord){
word = newWord;
}
Upvotes: 2
Reputation: 83
Try a getWord() and a setWord(String word)
Function Within mainClass and go from there.
Upvotes: 1