定义
- 类方法(静态方法):static关键字修饰的方法;因为 类方法的使用不依赖于对象的是否已经创建了。所以可以通过“类.方法”直接调用;
- 实例方法:用"对象.方法"的方式,必须依赖对象被创建后才能使用。
package test11;
/**
* 在类方法(静态方法)中调用本类的类方法时可直接调用
* 非静态的方法(实例方法)用"对象.方法"的方式,必须依赖对象被创建后才能使用
*
*补充:Java中,null是一个关键字,用来标识一个不确定的对象。
*因此可以将null赋给引用类型变量,但不可以将null赋给基本类型变量。
*null本身虽然能代表一个不确定的对象,但就null本身来说,
*它不是对象,也不知道什么类型,也不是java.lang.Object的实例。
*/
public class StaticTest {
//类方法
private static void testMethod2(){
//在类方法中调用本类的类方法时可直接调用
testMethod();
//在类方法中不能使用this关键字
//this.testestMethod();//编译失败
}
//类方法
private static void testMethod(){
System.out.println("testMethod");
}
//实例方法
private void testMethod3(){
System.out.println("这是一个实例方法");
}
//main()方法也是一个类的方法
public static void main(String[] args) {
//对方法的调用
StaticTest.testMethod();
//null可以被强制类型转换成任意类型(不是任意类型对象)
((StaticTest)null).testMethod();
StaticTest.testMethod2();
//对实例方法的调用,需要通过类的对象进行调用
new StaticTest().testMethod3();
}
}