Answer the question
In order to leave comments, you need to log in
Correct call to methods from other classes?
Learning Java, writing a parser. I want to ask advice about the correctness of calling methods from other classes.
I have classes, each of which implements methods for scanning some information.
For example, the Address class implements the search for an address and search for a link on the map and has corresponding methods getAddress() и getMapUrl().
. There are a lot of classes and methods, so I put the creation of instances in a separate class, it turns out I create an instance of Info info = new Info () once; and then to refer to the method I write like this: info.newAddress.getAddress();
(newAddress - creates a new instance of Address)
Actually, I would like to know whether it is right to do this, or is there some more reasonable way.
Answer the question
In order to leave comments, you need to log in
You somehow misunderstand the essence of OOP. Classes do not serve to group methods (in which you see only procedures), modules exist for this. In OOP, classes serve the purpose of encapsulating data. But if you use the class as a bunch of procedures, then creating an instance of such a class does not make sense, it is better to declare all methods as static and call them from the class itself without creating an instance. Only this approach has nothing to do with OOP.
nirvimel tells you correctly, you need to decide what you are using the classes for, i.e. pull up the "materiel" :)
If you just need "groupings" of methods, then you need to make classes like AddressUtils - i.e. auxiliary class, which will have static methods that will do some specific actions.
Those. you have, for example, the Address class:
public class Address {
String street;
String house;
String flat;
// getters
// setters
}
public class AddressUtils {
public static String getAddressString(Address address) {
if (address == null) {
return "";
}
StringBuilder sb = new StringBuilder("");
sb = sb.append(address.getStreet() == null || address.getStreet().isEmpty() ? "" : address.getStreet());
sb = sb.append(address.getHouse() == null || address.getHouse().isEmpty() ? "" : address.getHouse());
sb = sb.append(address.getFlat() == null || address.getFlat().isEmpty() ? "" : address.getFlat());
return sb.toString();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question