面向对象——static关键字详解

面向对象——static关键字详解

static关键字:

  • static关键字修饰的属性和方法放在静态存储区
  • 静态方法和静态属性是和类一起加载的(最早加载的)
  • 静态方法只能调用静态方法/属性,不能调用非静态方法/属性(静态方法加载时,非静态方法还未加载完成)
  • 非静态方法可以调用静态方法/属性

final关键字::如果这个类被final定义了,其他的类就不能继承此类了!!!

package(包)com.du.OOP.demo07:类Person(static关键字详解)

package com.du.OOP.demo07;

//如果这个类被final定义了,其他的类就不能继承此类了!!!
public final class Person {

    //赋初始值
    {
        System.out.println("匿名代码块");//代码块(匿名代码块)
    }

    //只执行一次
    static{
        System.out.println("静态代码块");//静态代码块
    }

    public Person() {
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person person1 = new Person();//1.打印:静态代码块 2.打印:匿名代码块 3.打印:构造方法

        Person person2 = new Person();//1.打印:匿名代码块 2.打印:构造方法
        //由此可以得出结论:静态代码块只执行一次!!!
    }
}

package(包)com.du.OOP.demo07:类Student(static关键字详解)

package com.du.OOP.demo07;

//static
public class Student {

    private static int age;//静态变量
    private double score;//非静态变量

    public void run(){
        System.out.println("run!");
        go();//合法,非静态方法可以调用静态方法
    }
    public static void go(){
        System.out.println("go!");
        //run();//报错,不合法,静态方法只能调用静态方法,不能调用非静态方法
    }

    //main()方法也是static方法!!!
    public static void main(String[] args) {
        Student s1 = new Student();

        //static属性
        System.out.println(Student.age);//直接用Student类调属性
        //System.out.println(Student.score);//报错:score不是在静态字段
        System.out.println(s1.age);//通过实例对象s1调属性
        System.out.println(s1.score);

        //static方法
        //Student.run();//报错,无法直接调用,必须先将Student进行实例化
        //run();//同样报错
        new Student().run();
        Student.go();//go()静态方法可以直接调,
        go();//可以正常调用

    }
}

package(包)com.du.OOP.demo07:类Test(static关键字详解)

package com.du.OOP.demo07;

import static java.lang.Math.random;

public class Test {

    public static void main(String[] args) {

        System.out.println(Math.random());//如果想直接调用random()方法,则可以导入这个方法:import static java.lang.Math.random;注:必须使用static关键字
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

studyingdda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值