Fundamentos do método estático Java, classe, variável e bloco
Publicados: 2019-12-13
O que é estático em Java?
- A palavra-chave estática pode ser usada com classe, variável, método e bloco.
- Membros estáticos não pertencem a nenhuma instância específica.
- Membros estáticos pertencem apenas à classe.
- Depois de tornar um membro estático, você pode acessá-lo sem nenhum objeto.
Você tem alguma das perguntas abaixo?
- Você poderia escrever as melhores práticas de métodos estáticos Java?
- O que são métodos estáticos Java na interface?
- Tem uma pergunta sobre métodos estáticos Java vs singleton?
- Desempenho de métodos estáticos Java vs métodos de instância
- Métodos e variáveis estáticos Java
- Métodos estáticos Java vs não estáticos
- Métodos estáticos Java em classe abstrata
A palavra-chave static pode ser usada em 3 cenários:
- Variáveis estáticas
- Métodos estáticos
- Blocos estáticos de código.
variável estática (palavra-chave "estática" = Variáveis de classe)

Em Java Variáveis podem ser declaradas com a palavra-chave “ static
”.
Exemplo: static int y = 0;
Quando uma variável é declarada com a palavra-chave static
, ela é chamada class variable
. Todas as instâncias compartilham a mesma cópia da variável. Uma variável de classe pode ser acessada diretamente com a classe, sem a necessidade de criar uma instância.
Nenhuma palavra-chave “estática” = variáveis de instância
Sem a palavra- static keyword
, ela é chamada de instance variable
e cada instância da classe tem sua própria cópia da variável.
Exemplo: static int crunchify_variable_name
;
- As variáveis estáticas são compartilhadas entre todas as instâncias da classe.
- Uma das principais razões pelas quais você precisa dele quando deseja fazer muito gerenciamento de memória.
- Para todas as variáveis estáticas – haverá apenas uma única cópia disponível para você usar.
- Você absolutamente não precisa de um objeto de classe para acessar a variável estática.
- Basta usá-lo diretamente. Você não precisa
object.StaticVariable
- Basta usá-lo diretamente. Você não precisa
O que é bloco estático?
O bloco estático é um bloco de instruções dentro de uma Java class
que será executado quando uma classe for carregada pela primeira vez na JVM.
Você pode substituir o método privado em Java?
- Bem não. Os métodos privados não podem ser substituídos, pois não estão disponíveis para uso fora da classe.
Por que não podemos substituir métodos estáticos em Java?
- Métodos estáticos também não podem ser substituídos, pois fazem parte de uma classe e não de um objeto
Podemos acessar variáveis não estáticas em contexto estático?
- Para poder acessar variáveis não estáticas de seus métodos estáticos, elas precisam ser variáveis de membro estáticas.
Detalhes sobre o método estático
- Como identificar? Basta verificar isso primeiro. Você precisa de um objeto de classe para acessar o método estático? Se você não precisa de um objeto, então é o método estático.
- Você precisa usar a palavra-chave estática para especificar o método estático
- É melhor usar a palavra-chave static se esse método não for alterado em todo o projeto em tempo de execução.
- Você não pode substituir o método estático.
Vamos dar uma olhada nos Exemplos abaixo:
Exemplo 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package crunchify . com . tutorials ; /** * @author Crunchify.com * */ public class CrunchifyStaticMethodMain { public static void main ( String args [ ] ) { String [ ] crunchifyObject = new String [ 3 ] ; crunchifyObject = new String [ ] { "Google" , "Facebook" , "Crunchify" } ; // creating instnace CrunchifyStaticMethodMain object = new CrunchifyStaticMethodMain ( ) ; object . crunchifyTestMethod ( crunchifyObject ) ; } /* * Check this out: Let's understand little more... * * Here method crunchifyTestMethod is defined as * public void crunchifyTestMethod(String[]) * so it is "non-static". It can't be called unless it is called on an instance of CrunchifyStaticMethodMain. * * If you declared your method as * public static void crunchifyTestMethod(int[]) * then you could call: CrunchifyStaticMethodMain.crunchifyTestMethod(arr); within main without having created an instance for it. */ public void crunchifyTestMethod ( String [ ] crunchifyObject ) { for ( int i = 0 ; i < crunchifyObject . length ; i ++ ) System . out . println ( crunchifyObject [ i ] ) ; } } |
Confira a explicação no above code block
. Temos que criar uma instância de Class para acessar o método não estático.
Exemplo-2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com . crunchify . tutorials ; /** * @author Crunchify.com */ public class CrunchifyStaticDeclaration { // 1st static block static { System . out . println ( "\nI'm static block 1.." ) ; setTestString ( "This is static block's String" ) ; setTestValue ( 2 ) ; } // 2nd static blocks in same class static { System . out . println ( "\nI'm static block 2.." ) ; } // static variable example private static int testValue ; // kept private to control it's value through setter public int getTestValue ( ) { return testValue ; } // static method example public static void setTestValue ( int testValue ) { if ( testValue > 0 ) CrunchifyStaticDeclaration . testValue = testValue ; System . out . println ( "setTestValue method: " + testValue ) ; } public static String testString ; /** * @return the testString */ public static String getTestString ( ) { return testString ; } /** * @param testString the testString to set */ public static void setTestString ( String testString ) { CrunchifyStaticDeclaration . testString = testString ; System . out . println ( "setTestString method: " + testString ) ; } // static util method public static int subValue ( int i , int . . . js ) { int sum = i ; for ( int x : js ) sum -= x ; return sum ; } } |
Agora vamos fazer o teste:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com . crunchify . tutorials ; /** * @author Crunchify.com */ public class CrunchifyStaticExample { public static void main ( String [ ] args ) { CrunchifyStaticDeclaration . setTestValue ( 5 ) ; // non-private static variables can be accessed with class name CrunchifyStaticDeclaration . testString = "\nAssigning testString a value" ; CrunchifyStaticDeclaration csd = new CrunchifyStaticDeclaration ( ) ; System . out . println ( csd . getTestString ( ) ) ; // class and instance static variables are same System . out . print ( "\nCheck if Class and Instance Static Variables are same: " ) ; System . out . println ( CrunchifyStaticDeclaration . testString == csd . testString ) ; System . out . println ( "Why? Because: CrunchifyStaticDeclaration.testString == csd.testString" ) ; } } |
Saída:
1 2 3 4 5 6 7 8 9 10 11 |
I 'm static block 1.. setTestString method: This is static block' s String setTestValue method : 2 I ' m static block 2.. setTestValue method : 5 Assigning testString a value Check if Class and Instance Static Variables are same : true Why ? Because : CrunchifyStaticDeclaration . testString == csd . testString |
Espero que você realmente obtenha boas informações sobre o método estático, variável e blocos.

Deixe-nos saber se você enfrentar algum problema ao executar o programa acima ou tiver um problema para entender a palavra-chave estática em Java.