Previously saw a technology Daniel wrote a static and non-static members, static and non-static methods of the respective differences, feel very good, write a small program here to illustrate these differences.
1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
package
com.liaojianya.chapter5;
/**
* This program will demonstrate the use of static method.
* @author LIAO JIANYA
*
*/
public class
StaticTest
{
public
static
void
main(String[] args)
{
System.out.println(
"用对象调用非静态方法"
);
MyObject obj =
new
MyObject();
obj.print1();
System.out.println(
"用类调用静态方法"
);
MyObject.print2();
} }
class
MyObject
{
private
static
String str1 =
"staticProperty"
;
private
String str2 =
"nonstaticProperty"
;
public
MyObject()
{
}
public
void
print1()
{
System.out.println(str1);
//非静态方法可以访问静态域
System.out.println(str2);
//非静态方法可以访问非静态域
print2();
//非静态方法可以访问静态方法
}
public
static
void
print2()
{
System.out.println(str1);
//静态方法可以访问静态域
// System.out.println(str2); //静态方法不可以访问非静态域
// print1();//静态方法不可以访问非静态方法
}
}
|
Output Result:
Calling a non-static method with an object Staticpropertynonstaticpropertystaticproperty calls a static method with a class Staticproperty
If you remove the comment symbol from the comment section, you will get two error:
Error 1 caused when the first comment is removed:
Cannot make a static reference to the Non-static field str2
Error 2 After the second comment is removed:
Cannot make a static reference to the Non-static method Print1 () from the type MyObject
Conclusion: Static methods cannot access non-static member variables, and static methods cannot access non-static methods.
In fact, it is a sentence: static can not access non-static, but not static access to static and can be accessed non-static.
At the same time: static methods can be called directly through the class name, without object invocation, thus reducing the cost of instantiation.
Static and non-static differences in Java