static的用法

static的用法实例

package com.lyh.oop1;
//static
public class StaticDemo {
    private static int age;//静态的变量
    private double score;//非静态的变量
    //非静态的方法可以访问静态方法,
    // 因为静态方法是和类一起加载到内存中的
    public void run(){

    }
    //静态方法无法调用非静态方法
    public static void go(){

    }
    public static void main(String[] args) {
        StaticDemo s1 = new StaticDemo();
        System.out.println(StaticDemo.age);
        System.out.println(s1.age);
        System.out.println(s1.score);
        go();
    }

}

package com.lyh.oop1;

public class StaticCode {
    //负初始值
    {
        //代码块(匿名代码块),放在构造器之前,其次执行
        System.out.println("匿名代码块");
    }
    static{
        //静态代码块,首先执行,且只执行一次
        System.out.println("静态代码块");
    }
    public StaticCode(){
        //构造方法,最后执行
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        StaticCode person = new StaticCode();
        System.out.println("==========");
        StaticCode person2 = new StaticCode();

    }
}

package com.lyh.oop1;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;

public class StaticTest {
    public static void main(String[] args) {
        System.out.println(Math.random());
        //导入静态包之后
        System.out.println(random());
        System.out.println(PI);
    }
}
//当一个类被final定义之后无法被其他类继承
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值