What is the sense of an attribute being private and Static at the same time in a class?

Asked

Viewed 1,876 times

16

I’m studying about the design pattern singleton, and in a code snippet on java, I came across a situation where I was in doubt. Below is the excerpt of the code:

public class Conexao {

    private static Conexao instance = new Conexao();

    public static Conexao getInstance() {
        return instance;
    }

    private Conexao() {
    }

    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://endereco_do_banco.ws", "login", "senha");
        return conn;
    }

}

My doubt is in the stretch private static Conexao instance = new Conexao(); , what is the sense of creating an attribute private and static at the same time? If we assign it as private is because we want it not to be visible to other classes, and putting it as static, we would be leaving it visible to other classes, this is not contradictory?

4 answers

14


If we assign it as private is because we want it not to be visible to other classes, and putting it as Static, we would be leaving it visible to other classes, this is not contradictory?

Although its access modifier definition private is correct, you missed the setting of the modifier static (I’ll explain then what it really does) and what you said about it would fit just to describe the access modifier public. You probably got confused in the definitions.

The modifier static makes a declared member with it accessible through the type where it was declared and not through a type instance. That is, a property or a method declared as static can be accessed directly without the need for you to enter the class where it was declared (Classe1.Propriedade1 = "Oi"; or Classe1.Metodo1();).

Note that when it is necessary to create a class instance when the member does not have the modifier static (var obj = new Classe1(); obj.Propriedade1 = "Oi"; obj.Metodo();).

Already the access modifier public this yes, leaves members of a type (class) or a type itself, accessible without any restriction.

I recommend you take a look at the modifier setting static to better understand it, and also in defining the access modifier public.

what is the sense of creating an attribute private and static at the same time?

I don’t think it’s necessary to answer that first question now, but come on.

The answer is simple, the standard design Singleton requires it to be done this way.

As described in the Wikipedia article, to implement the standard the class must have the following characteristics:

  • A private static field needs to be created in the class to store the only instance of the class that will be distributed by the application;
  • A public and static method that will return the class instance that is stored in the field defined in the previous point;
  • Instances of the class can only be created within itself through the method defined in the previous point, for this it is necessary that the class has a private constructor.

But note that setting fields like private static is not restricted only to this standard, you may come across situations within a project that may benefit from a field declared in this way.

  • 2

    Got it @Zignd, thank you so much for the explanation! Now I realized that my vision on Static is completely wrong, I need to study more about it.

  • 2

    You’re welcome, at least I was able to help you. (^-^)

  • 2

    Another question, but what is the point of assigning an access modifier, such as private, to a Static member? Where private access would limit access to a Static member?

  • 1

    @Duds the advantage of doing this is that you have control of how to offer this static instance. You may for example want to perform some operations in that instance before passing it on to the person who requested it. To do this you can create a property that only owns the get and modify the instance as you want inside the block get before returning it.

10

It is not because its definition is wrong. The understanding of what the private does is correct.

But the static does not say that it is visible to other classes, it says that the member belongs to the class and not to an instance of the class. It has nothing to do with visibility, it has to do with the property of the data, with where it will be stored and therefore through which component of the language it will be accessed. It is a scope modifier. It defines the lifespan of the member.

Just as members of the panel may be public or private members of the class may also.

A static field is one that is available in a uniquely shaped class for the entire application. It is not bound to an instance of the class. It belongs to the class itself and is shared by all instances (objects) of this class created during the execution of the application, the lifetime is the entire application. While the lifetime of an instance member is the same as the lifetime instance to which it belongs.

A static field exists within the class, but its visibility is defined by another modifier.

A private field is one that can only be seen/accessed within the class ,all that is private is implementation detail. It means you don’t want anyone to know what you’re like internally (not in the sense of industrial secrecy) giving you a chance to change whenever you want, however you want.

What is public is part of the API, is something you commit to keep stable, after all anyone can access it. You have no control over who accessed and how.

Scope and visibility are different things. The location of data existence is the scope. Where there can be a request for access to this data, that is, where it can be accessed, is the visibility.

And it’s simple to test and verify this since you have two static members each with a different visibility. The two are variables belonging to the class and not to an instance. Already the getConnection() is the case.

Try to access the field instance from somewhere outside this class. You can do it the way you want (except for reflection or another trick that goes over the language:) ), you can’t, just access it within the class.

On the other hand the method getInstance() is static and public. Try to access from outside. Can.

That’s all.

  • But then @bigown, if it has to do with the ownership of the die and the location where it will be stored, what is the point of a Static having private access? How a private modifier influences access to a Static member?

  • I improved, I don’t know if I can be clearer than that. But apparently you thought the other answer was clearer. I don’t think she explains anything you asked her, but that’s okay. To tell you the truth she’s more disinterested.

  • Elaborate on the fact that my answer "uninform", @bigown. Now I’m curious.

  • The answer does not answer exactly what was asked. But if the AP thinks so, it will do what . But the biggest problem is the comment that speaks in "static instance" (?!?!?) and everything there does not make sense..

  • 1

    That’s the right answer. There’s nothing wrong with the other answer, but it doesn’t answer the question that was asked. + 1

  • Okay, I made a correction to my answer, now she’s answering the question. @jbueno

  • @Zignd I think the only answer that fully answers the question "What is the sense of an attribute being private and Static at the same time" is mine.

Show 2 more comments

5

The reasons for private static sane:

  • private by not wanting it to be visible outside the class.

  • static because a field cannot be referenced static in a method static as is the case getInstance()

2

Buddy, I know it’s been years, but other people might have the same question.

Our friend Zignd’s answer is the best, most correct, but difficult to understand.

  1. Your definition of Static is wrong. But why do you think that? Reason: in C a Static FUNCTION is visible only to its source file. In Java a Static method means something else.

  2. In Java, a Static method means that it is UNIQUE to all its Objects. It always does the same thing. Therefore, to call a Static method it is not necessary to instantiate an object. Example:

.

public class Main
{
        public static void main(String[] args)
        {
                ClasseB objB;
                objB  = new ClasseB(); // Não precisa instanciar objB para usar getValor
                System.out.println("Ola\n");
                //
                System.out.println("Valor= " + ClasseB.getValor()); // Funcionaria mesmo sem instanciar objB, pois está chamando o metodo static.
                System.out.println("Valor= " + objB.getValor()); // Está chamando o objB, logo só funciona se instanciar obj. (objB  = new ClasseB();)
                System.out.println("Valor= " + ClasseB.getValor());


        }
}

class ClasseB {

    private static int valor = 0;

    public static int getValor()
    {
        valor ++;
        return valor;
    }

    public ClasseB()
    {

    }
}

Exit:

MEU@PC:~/tmp$ 
MEU@PC:~/tmp$ javac Main.java
MEU@PC:~/tmp$ java Main
Ola

Valor= 1
Valor= 2
Valor= 3

System.out.println is a Static method, so you do not need the instance to use. (Make System system system = new System());

  1. Static variables are similar in C and Java.

Think of them as GLOBAL variables for all objects, but they are only accessible within the scope where it was created. In the case of java, within its Class (or object) and global between the objects.

What do you mean? When calling the program, the Static variable is created. It will remain in memory until the program is finished. But it is inaccessible outside her scope (of the keys where it was created {}).

That is why it is necessary

public class Main
{
        public static void main(String[] args)
        {
                ClasseA objA = new ClasseA();
                ClasseA objB = new ClasseA();

                System.out.println("System.out.print nao precisa de NEW por ser static.\n");

                System.out.println("ClasseA.valorStatico= " + ClasseA.getValorStatico());
                System.out.println("objA.valorStatico= " + objA.getValorStatico());
                System.out.println("ClasseA.valorStatico= " + ClasseA.getValorStatico());
                // System.out.println("objA.valorStatico= " + ClasseA.getValorLocal()); <- Erro de compilacao, método não é estatico.
                System.out.println("objA.valorLocal= " + objA.getValorGlobalLocal());
                System.out.println("objA.valorLocal= " + objA.getValorGlobalLocal());
                System.out.println("objA.valorStatico= " + objA.getValorStatico());

// PARA B
                System.out.println("ClasseA.valorStatico= " + ClasseA.getValorStatico());
                System.out.println("objB.valorStatico= " + objA.getValorStatico());
                System.out.println("ClasseA.valorStatico= " + ClasseA.getValorStatico());
                // System.out.println("objB.valorStatico= " + ClasseB.getValorLocal()); <- Erro de compilacao, método não é estatico.
                System.out.println("objB.valorLocal= " + objA.getValorGlobalLocal());
                System.out.println("objB.valorLocal= " + objA.getValorGlobalLocal());
                System.out.println("objB.valorStatico= " + objB.getValorStatico());

        }
}

class ClasseA {

    private static int valorStatico = 0;
    private int valorGlobalLocal =0;

    public static int getValorStatico()
    {
        return valorStatico++;
    }
    public int getValorGlobalLocal()
    {
        return valorGlobalLocal++;
    }

    public ClasseA()
    {


    }
}

So we’ll have the next exit:

java Main
System.out.print nao precisa de NEW por ser static.

ClasseA.valorStatico= 0
objA.valorStatico= 1
ClasseA.valorStatico= 2
objA.valorLocal= 0
objA.valorLocal= 1
objA.valorStatico= 3
ClasseA.valorStatico= 4
objB.valorStatico= 5
ClasseA.valorStatico= 6
objB.valorLocal= 2
objB.valorLocal= 3
objB.valorStatico= 7

Note, Classea.valorStatico is incremented either when it is called by objA, objB or Classeb.

In my understanding, the simple fact that you make the variable instance as Static, He’s already a Singleton. These examples of Singleton codes are examples for various languages. In Java only instantiate as var as Static, if var = null, then you need to create the connection with DB.

Now, the private Conexao() (private in Constructor), makes your class never instantiated by another class, only by itself. Therefore, only one Static method (from the Connected class) can allocate the object. This serves to have full control over how to create the object.

If in my class the constructor were private:

classe ClasseB
{ 
...
    private ClasseB()
    {


    }
}

It would never be possible to instantiate externally B:

ClasseB varB = new ClasseB() // daria erro

Browser other questions tagged

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