靜態方法使用靜態關鍵字定義,但是聲明實例變數時不使用靜態關鍵字。通常情況下,我們不能透過靜態方法存取實例變數。
在本文中,我們將建立一個實例變量,然後透過一個靜態方法來檢查該實例變數的可訪問性。首先讓我們來了解靜態方法和實例變數。
在程式語言的上下文中,變數是包含任何類型資料的容器的名稱。我們可以說它是一個儲存單元。
Data_Type nameOfvariable = values [optional];
A variable can be initialized at the time of declaration or we can initialize it when required in the whole program. But value must be of the same data type as specified at the time of declaration.
String str; // only declaration int price = 59; // declaration and initialization str = “Tutorix”; // initialization of ‘str’
Instance variables are one of the types of variables that are non-static. They are declared inside class but outside of every method scope of that class. They are accessible to all methods that thatong to class class. can be public, private, protected, 或 default. If we don't mention any access specifier then variable will be initialized with default access specifier.
Static methods are defined using non access modifier static keyword. Normally, we call a method by creating an object of its class but static methods can be called without using objects。 class not to the instance of that class.
Class_name.static_method_name
For example, most of the members of inbuilt class Math is static. We can use them directly without creating its object.
public class Main { public static void main( String[] args ) { double x = 6.55; double y = 4.32; System.out.println(" Ceil value of x: " + Math.ceil(x) ); System.out.println(" Floor value of y: " + Math.floor(y) ); System.out.println(" Value of PI = " + Math.PI); } }
Ceil value of x: 7.0 Floor value of y: 4.0 Value of PI = 3.141592653589793
上面的範例說明了Math類別的靜態方法ceil()和floor()的使用。我們可以看到,在我們的程式中直接使用了它們,而不需要建立任何Math類別的物件。
We already mentioned earlier in this article that we can’t access instance variables by a static method directly, we can only access them by creating an instance or object of the class.
##Example
public class Main { public String str = "Tutorialspoint"; public static void main(String []args) { System.out.println(" Accessing instance variable " + str); } }
輸出
Main.java:4: error: non-static variable str cannot be referenced from a static context System.out.println(" Accessing instance variable " + str); ^ 1 error
public class Main { public String str = "Tutorialspoint"; public static void main(String []args) { Main obj = new Main(); // creating object using new keyword // To access the instance variable ‘str’ System.out.println(" Accessing instance variable: " + obj.str); } }
Accessing instance variable: Tutorialspoint
以上是Java程式用於透過靜態方法檢查實例變數的可訪問性的詳細內容。更多資訊請關注PHP中文網其他相關文章!