Fondamenti di Java Static Method, Class, Variable e Block
Pubblicato: 2019-12-13
Che cos'è statico in Java?
- La parola chiave statica può essere utilizzata con classe, variabile, metodo e blocco.
- I membri statici non appartengono a nessuna istanza specifica.
- I membri statici appartengono solo alla classe.
- Dopo aver reso statico un membro, puoi accedervi senza alcun oggetto.
Hai una delle seguenti domande?
- Potresti annotare le migliori pratiche dei metodi statici Java?
- Che cosa sono i metodi statici Java nell'interfaccia?
- Hai una domanda sui metodi statici Java rispetto a singleton?
- Prestazioni dei metodi statici Java rispetto alle prestazioni dei metodi di istanza
- Metodi e variabili statici Java
- Metodi statici Java vs non statici
- Metodi statici Java in classe astratta
La parola chiave static può essere utilizzata in 3 scenari:
- Variabili statiche
- Metodi statici
- Blocchi di codice statici.
variabile statica (parola chiave "statica" = variabili di classe)

In Java le variabili possono essere dichiarate con la parola chiave “ static
”.
Esempio: static int y = 0;
Quando una variabile viene dichiarata con la parola chiave static
, viene chiamata class variable
. Tutte le istanze condividono la stessa copia della variabile. È possibile accedere a una variabile di classe direttamente con la classe, senza la necessità di creare un'istanza.
Nessuna parola chiave "statica" = variabili di istanza
Senza la static keyword
, si chiama instance variable
e ogni istanza della classe ha la propria copia della variabile.
Esempio: static int crunchify_variable_name
;
- Le variabili statiche sono condivise tra tutte le istanze della classe.
- Uno dei motivi principali per cui ne hai bisogno quando vuoi fare molta gestione della memoria.
- Per tutte le variabili statiche, sarà disponibile una sola copia da utilizzare.
- Non hai assolutamente bisogno di un oggetto di classe per accedere alla variabile statica.
- Basta usarlo direttamente. Non hai bisogno di
object.StaticVariable
- Basta usarlo direttamente. Non hai bisogno di
Cos'è il blocco statico?
Il blocco statico è un blocco di istruzioni all'interno di una Java class
che verrà eseguito quando una classe viene caricata per la prima volta nella JVM.
Puoi sovrascrivere il metodo privato in Java?
- Beh no. I metodi privati non possono essere ignorati in quanto non sono disponibili per l'uso al di fuori della classe.
Perché non possiamo sovrascrivere i metodi statici in Java?
- Inoltre, i metodi statici non possono essere sovrascritti poiché fanno parte di una classe anziché di un oggetto
Possiamo accedere a variabili non statiche in un contesto statico?
- Per poter accedere a variabili non statiche dai tuoi metodi statici, devono essere variabili membro statiche.
Dettagli sul metodo statico
- Come identificare? Basta controllare prima questo. Hai bisogno di un oggetto di classe per accedere al metodo statico? Se non hai bisogno di un oggetto, allora è il metodo statico.
- È necessario utilizzare la parola chiave static per specificare il metodo statico
- È meglio utilizzare la parola chiave static se quel metodo non cambierà durante il progetto in fase di esecuzione.
- Non puoi sovrascrivere il metodo statico.
Diamo un'occhiata agli esempi seguenti:
Esempio 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 ] ) ; } } |
Dai un'occhiata alla spiegazione nel above code block
. Dobbiamo creare un'istanza di Class per accedere al metodo non statico.
Esempio-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 ; } } |
Ora facciamo il test:
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" ) ; } } |
Produzione:
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 |
Spero che tu abbia davvero buone informazioni sul metodo statico, sulla variabile e sui blocchi.

Facci sapere se riscontri problemi con l'esecuzione del programma sopra o se hai problemi con la comprensione della parola chiave statica in Java.