Handling object only in methods

Asked

Viewed 48 times

0

When I create an instance of a class I can access its attributes only when I’m inside a method, why? In the example below I can give a set in the method main() but not within the class, why?

public class App {

    Pessoa p = new Pessoa();
    p.

    public static void main(String[] args){
        System.out.println("teste");
        Pessoa pessoa = new Pessoa();
        pessoa.setNome("Teste");
    }
}

1 answer

3


Classes are data structures, they serve only to declare what must be in this structure, it cannot have algorithms (have it done), the place of algorithms is the method. Classes do not guarantee execution order, methods yes, it is one line after another, all data manipulation has to be in the method. In fact, I don’t even see the point of doing anything outside of them, if you think there’s a reason you should justify it.

Of course some language can allow something of the kind in a limited way (in the background it would only be syntax sugar, would still have run in a method even if in disguise, C# does a lot of it, but only to initialize a value in a field or declared property), but would need to have a motivation, it can’t be just because someone wants it, or because it’s cute, everything that a language allows generates a cost to it, an obligation that it will always have to carry forever.

The term attribute there was mistakenly used, I mean members. But the problem is not even to access the member, but to do a processing, and to access a member would be a form of processing. Nor will I say that what you have learned you call attribute is actually called field.

  • Not that I see sense, it’s just to dispel doubt.

  • There is a guaranteed execution field that is indicated by a block {..} no identifier, executed when creating the object (similar to what static { ...} makes for classes). It is good as an addendum of builders to ensure some internal state that needs to be created in a non-trivial way.

  • 1

    @Jeffersonquesado that it is a method, it just has no name (internally it has).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.