I imagine you have something like this currently where everything is in one big class:
public class Main1 {
private String street;
private String city;
public Main1(String street, String city) {
this.street = street;
this.city = city;
}
private void printAddress() {
System.out.println(street);
System.out.println(city);
}
public static void main(String[] args) {
Main1 ex = new Main1("1 Main street", "Springfield");
ex.printAddress();
}
}
As a first step I would move some of the data out of your class into another class, grouping like data together (in this case it's obviously an Address) and then reference that class in your original class, maybe:
class Address {
private String street;
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
public String getCity() {
return city;
}
public String getStreet() {
return street;
}
}
public class Main {
private void printAddress(Address address) {
System.out.println(address.getStreet());
System.out.println(address.getCity());
}
public static void main(String[] args) {
Main ex = new Main();
Address address = new Address("1 Main street", "Springfield");
ex.printAddress(address);
}
}
After that you might notice that some of the functionality might also logically belong on the class you just pulled out and you can provide methods on the new class to provide that functionality:
class Address {
private String street;
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
public String formattedAddress() {
return street + "\n" + city;
}
}
public class Main {
public static void main(String[] args) {
Main ex = new Main();
Address address = new Address("1 Main street", "Springfield");
System.out.println(address.formattedAddress());
//ex.printAddress(address);
}
}