4.23 关键字static

在这里插入图片描述
在这里插入图片描述
Chinese

package day08;

public class Chinese {
//    String country;
    String name;//实例变量,只有实例化之后才能使用
    String age;//实例变量,只有实例化之后才能使用

    static String country;//类变量,不用实例化就能使用
}

TestChinese

package day08;

public class TestChinese {

    public static void main(String[] args) {
//        Chinese c1=new Chinese();
//        c1.country="中国";
//
//        Chinese c2=new Chinese();
//        c2.country="中国";
//
//        Chinese c3=new Chinese();
//        c3.country="中国";
//
//         我们发现,上述每一个都要写“中国”,这样太麻烦,进而我们采用关键字static修饰变量,并在
//          测试类里写Chinese.country=“中国”
        Chinese.country="中国";
        Chinese c1=new Chinese();
        Chinese c2=new Chinese();
        Chinese c3=new Chinese();
        System.out.println(c1.country);
        //我们访问时,也不用上面的方法了,通常使用下面的方法
        System.out.println(Chinese.country);
    }
}

在这里插入图片描述
那么同样的,通过以上的分析,我们也可以用static修饰方法(比如说,main方法就是用static修饰过的)。
Chinese

package day08;

public class Chinese {
//    String country;
    String name;//实例比变量,只有实例化之后才能使用
    String age;//实例比变量,只有实例化之后才能使用

    static String country;//类变量,不用实例化就能使用

    public static void pp(){
        System.out.println("这个方法是static方法");
    }
}

TestChinese

package day08;

public class TestChinese {

    public static void main(String[] args) {
//        Chinese c1=new Chinese();
//        c1.country="中国";
//
//        Chinese c2=new Chinese();
//        c2.country="中国";
//
//        Chinese c3=new Chinese();
//        c3.country="中国";
//
//         我们发现,上述每一个都要写“中国”,这样太麻烦,进而我们采用关键字static修饰变量,并在
//          测试类里写Chinese.country=“中国”
        Chinese.country="中国";
        Chinese c1=new Chinese();
        Chinese c2=new Chinese();
        Chinese c3=new Chinese();
        System.out.println(c1.country);
        //我们访问时,也不用上面的方法了,通常使用下面的方法
        System.out.println(Chinese.country);

        Chinese.pp();
    }
}

运行截图
在这里插入图片描述

例如我们平常会使用到的工具类
Utils

package day08;
//在未来的开发中,可能会多次使用一个方法,在大量的基础上,会发现代码的重复太多
//所以会创建一个“工具”类
public class Utils {
    //判断字符串是不是一个空字符串,true返回不空
    public static boolean isEmpty(String s){
        boolean flag=false;
        if (s!=null && !s.equals("")){
            flag=true;
        }
        return flag;
    }
}

TestUtils

package day08;

public class TestUtils {
    public static void main(String[] args) {
        String s="";
        System.out.println(s.isEmpty());

    }
}

运行截图
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值