static关键字

概述:

        是一个静态修饰符关键字,表示静态的意思,可以修饰成员变量和成员方法以及代码块

特点:

        被static修饰的成员变量是属于类的,叫做静态成员变量/类变量,会被该类的所有对象共有

使用:

        一、static 修饰的成员变量

class Person {
    // 定义成员变量
    String name;
    // 定义静态成员变量
    static String country;

    public Person(){}

    public Person(String name,String country){
        this.name = name;
        this.country = country;
    }
}

public class Tests {
    public static void main (String[] args) {
        // 实例化一个person对象,并传两个参数过去
        Person p = new Person("张三","中国");
        System.out.println(p.name + "," + p.country);

        Person p2 = new Person();
        //  当成员变量country被static修饰的话,会被该类的所有对象共享
        System.out.println(p2.name + "," + p2.country);
    }
}

输出结果:

 对比两次输出结果,不难看出,被static修饰的变量会被该类的其它对象所调用

        二、static修饰成员方法

class Person {

    //非静态方法
    public void method1(){
        System.out.println("Person method1");
    }

    //静态方法
    public static void method2(){
        System.out.println("Person method2");
    }
}

public class Tests {
    public static void main (String[] args) {
        /*
        *   static修饰成员方法:
        *       格式:权限修饰符 static 返回值类型 方法名称(方法列表){方法体}
        *       特点:被static修饰的成员方法叫做静态成员方法/类方法
        *       使用:
        *           对象名.静态成员方法(实参)--> 不推荐
        *           类名称.静态成员方法(实参)--> 推荐使用
        * */

        //  实例化一个Person对象
        Person person = new Person();
        person.method1();
        person.method2();

        //推荐:类名称调用类方法
        Person.method2();
    }
}

 static修饰的成员方法在调用时可以直接用  类名称.静态成员方法  ,这样使用会更便捷

不用再创建对象了,可以直接调用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值