I have 3 different classes in Java. FirstClass that has 2 Strings, ThirdClass that has 1 String, and SecondClass that needs access to those Strings. How can I access all of these Strings?
If there were 2 classes I would have done something like the following
public class FirstClass {
private String name;
private String lname;
public FirstClass(){
name = "John";
lname = "Watson";
new SecondClass(name, lname);
}
}
public class SecondClass{
new SecondClass(String name, String lname){
//doSomething
}
}
How can I have a ThirdClass with another String accessible from SecondClass?
I've searched a lot and nothing came up other than the solution with 2 classes. I don't want to do the following
public class FirstClass{
private String name;
private String lname;
public FirstClass(){
name = "John";
lname = "Watson";
new ThirdClass(name, lname);
}
}
public class ThirdClass{
private String location;
public ThirdClass(String name, String lname){
location = "Europe";
new SecondClass(name, lname, location);
}
}
public class SecondClass{
new SecondClass(String name, String lname, String location){
//doSomething
}
}
I also can't put all the Strings in one class. Is there a way that I can do it?
FirstClassandThirdClassinSecondClassto access the private instance fields fromFirstClassandSecondClass, you can creategetterandsetterfunctions inFirstClassandThirdClass. For details ofgetter/setterfunctions, see: Getters and Setters in Java Explained