静态与方法
调用静态和非静态方法:
调用非静态方法:也就是没有static修饰的方法体数据,需要进行【类 引用 = new 类名()】进行数据的实例化,然后通过【引用.方法名】进行调用。
调用静态方法:也就是有static修饰的方法体数据,直接通过【类名.方法名】调用
public class Customer {
// 姓名 :
String name;
// 无参构造方法
public Customer(){}
// 不带有static关键字的非静态方法
public void buyGoods(){
System.out.println(this.name+"在购物");
}
// 带有static关键字的静态方法
public static void toGoods(){
System.out.println(123456);
}
}
package textThis;
/**
* @author Monopkr
* @date 2022/5/14 - 9:10
*/
public class CustomerText {
public static void main(String[] args) {
// 调用非静态的方法
Customer c1 = new Customer();
c1.name = "张三";
System.out.println(c1.name);
c1.buyGoods(); // 可以对应修改到对应的name
Customer c2 = new Customer();
c2.name = "李四";
System.out.println(c2.name);
c2.buyGoods();
//调用static静态方法
Customer.toGoods();
}
}
综合:
package textThis;
/**
* @author Monopkr
* @date 2022/5/14 - 11:58
*/
public class CText {
public void doMethod1(){
System.out.println("这里是非静态的一级方法");
this.methods1(); // 调用二级非静态方法
CText.method2(); // 调用二级静态方法
}
public static void doMethod2(){
System.out.println("这里是静态的一级方法");
CText T1 = new CText(); // 调用二级非静态方法
T1.methods1();
CText.method2(); // 调用二级静态方法
}
public static void main(String[] args) {
CText T = new CText();
T.doMethod1();
System.out.println("--------------------");
CText.doMethod2();
}
public void methods1(){
System.out.println("二级非静态方法");
}
public static void method2(){
System.out.println("二级静态方法");
}
}
带有static的方法,其实既可以采用类名的方式访问,也可以采用引用的方式访问,但是即使采用引用的方式去访问,实际上执行的时候和引用指向的对象无关。不会出现空指针异常。
static的使用
静态变量:static修饰的变量: 如:static String country; 在类加载的时候初始化,不需要实例化对象,内存就开辟了。
静态代码块:
1、 语法格式: static{
java语句;
}
2、静态代码块在类加载时执行,并且只执行一次。
3、静态代码块在一个类中可以编写多个,并且遵循自上而下的顺序依次执行。
4、静态代码块的作用:
public class staticText{
static{
System.out.println("类加载");
}
public static void main (String[] args){