Fundamentos del método estático, clase, variable y bloque de Java
Publicado: 2019-12-13
¿Qué es estático en Java?
- La palabra clave estática se puede usar con clase, variable, método y bloque.
- Los miembros estáticos no pertenecen a ninguna instancia específica.
- Los miembros estáticos pertenecen únicamente a la clase.
- Una vez que convierte un miembro en estático, puede acceder a él sin ningún objeto.
¿Tiene alguna de las siguientes preguntas?
- ¿Podría escribir las mejores prácticas de métodos estáticos de Java?
- ¿Qué son los métodos estáticos de Java en la interfaz?
- ¿Tiene alguna pregunta sobre los métodos estáticos de Java frente a singleton?
- Rendimiento de los métodos estáticos de Java frente a los métodos de instancia
- Variables y métodos estáticos de Java
- Métodos estáticos de Java frente a no estáticos
- Métodos estáticos de Java en clase abstracta
La palabra clave estática se puede utilizar en 3 escenarios:
- Variables estáticas
- Métodos estáticos
- Bloques estáticos de código.
variable estática (palabra clave "estática" = Variables de clase)

En Java, las variables se pueden declarar con la palabra clave " static
".
Ejemplo: static int y = 0;
Cuando una variable se declara con la palabra clave static
, se denomina class variable
. Todas las instancias comparten la misma copia de la variable. Se puede acceder a una variable de clase directamente con la clase, sin necesidad de crear una instancia.
Sin palabra clave "estática" = Variables de instancia
Sin la static keyword
, se llama instance variable
y cada instancia de la clase tiene su propia copia de la variable.
Ejemplo: static int crunchify_variable_name
;
- Las variables estáticas se comparten entre todas las instancias de la clase.
- Una de las principales razones por las que lo necesita cuando desea administrar mucha memoria.
- Para todas las variables estáticas, solo habrá una copia disponible para su uso.
- Absolutamente no necesita un objeto de clase para acceder a la variable estática.
- Solo úsalo directamente. No necesitas
object.StaticVariable
- Solo úsalo directamente. No necesitas
¿Qué es el bloque estático?
El bloque estático es un bloque de declaración dentro de una Java class
que se ejecutará cuando una clase se cargue por primera vez en la JVM.
¿Puedes anular el método privado en Java?
- Bueno no. Los métodos privados no se pueden anular ya que no están disponibles para usar fuera de la clase.
¿Por qué no podemos anular los métodos estáticos en Java?
- Los métodos estáticos tampoco se pueden anular, ya que son parte de una clase en lugar de un objeto.
¿Podemos acceder a variables no estáticas en un contexto estático?
- Para poder acceder a variables no estáticas desde sus métodos estáticos, deben ser variables miembro estáticas.
Detalles sobre el método estático
- ¿Cómo identificar? Solo revisa esto primero. ¿Necesita un objeto de clase para acceder al método estático? Si no necesita un objeto, entonces es el método estático.
- Debe usar la palabra clave estática para especificar el método estático
- Mejor use la palabra clave estática si ese método no va a cambiar a lo largo de su proyecto en tiempo de ejecución.
- No puede anular el método estático.
Echemos un vistazo a los siguientes ejemplos:
Ejemplo 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 ] ) ; } } |
Consulte la explicación en above code block
. Tenemos que crear una instancia de Clase para acceder al método no estático.
Ejemplo-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 ; } } |
Ahora hagamos la prueba:
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" ) ; } } |
Producción:
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 realmente obtenga buena información sobre el método estático, la variable y los bloques.

Háganos saber si tiene algún problema al ejecutar el programa anterior o si tiene problemas para comprender la palabra clave estática en Java.