H
H
hell4eg2015-12-01 01:04:26
Java
hell4eg, 2015-12-01 01:04:26

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

2 answer(s)
N
nirvimel, 2015-12-01
@hell4eg

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.

A
Alexander Lukyanov, 2015-12-01
@sanluck

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
}

And you want that when you pass an instance of this class to your helper method, for example, the human-readable form of the address would be displayed:
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 question

Ask a Question

731 491 924 answers to any question