• 13.系统总结static


    static修饰属性和方法:
     1 package com.oop.demo08;
     2 
     3 //static :被static修饰的变量或者方法随类加载,从属于类,当然对象也可以调用
     4 public class Student {
     5 
     6     private static int age;//静态的变量 :在方法区  多线程会详解!
     7     private double score;//非静态的变量
     8 
     9     //非静态方法,从属于类,可以访问本类中的静态方法,因为静态方法在类创建时就加载了。
    10     public void run() {
    11         go();
    12     }
    13 
    14     //go()方法被static修饰,在当前类中可以用类打点调用,也可以直接用
    15     public static void go() {
    16 
    17     }
    18 
    19     //静态只能调用静态的
    20     public static void main(String[] args) {
    21         Student s1 = new Student();
    22 
    23         System.out.println(Student.age);
    24         System.out.println(s1.score);
    25         System.out.println(s1.age);
    26 
    27         new Student().run();
    28         Student.go();
    29         go();
    30 
    31     }
    32 }
    static:静态代码块
     1 package com.oop.demo08;
     2 
     3 public class Person {
     4 
     5     //2.赋初始值,随对象一起产生,而且在构造方法之前,也可以通过这种方式赋初始值
     6     {
     7         //代码块(匿名代码块),程序在执行的时候并不能主动调用这些模块,
     8         //是创建这个对象的时候,自动创建的,而且在构造器之前
     9         System.out.println("匿名代码块");
    10     }
    11 
    12     //1.只执行一次~
    13     static {
    14         //静态代码块:可以加载一些初始化的东西,
    15         //类一加载就直接执行,只执行一次
    16         System.out.println("静态代码块");
    17     }
    18 
    19     //3.
    20     public Person() {
    21         System.out.println("构造方法");
    22     }
    23 
    24     public static void main(String[] args) {
    25         Person person1 = new Person();
    26         System.out.println("==============");
    27         Person person2 = new Person();
    28     }
    29 
    30 }
    31 结果:
    32 静态代码块
    33 匿名代码块
    34 构造方法
    35 ==============
    36 匿名代码块
    37 构造方法
    父子类中:
    1 //被static修饰的方法无法被重写 
    好玩的:
     1 package com.oop.demo08;
     2 
     3 //静态导入包~可以不用Math打点调用了
     4 
     5 import static java.lang.Math.random;
     6 
     7 public class Test {
     8 
     9     public static void main(String[] args) {
    10         System.out.println(random());
    11     }
    12 
    13 }
  • 相关阅读:
    使用MailKit发送邮件
    移动APP设备锁功能开发中的问题
    Xamarin.Form指纹认证
    Android App安装启动时签名校验
    网络编程学习资料
    ASP.NET Core 2.1发布/部署到Ubuntu并配置Nginx反向代理实现ip访问
    @media用法解释
    CSS calc() 函数
    css3属性box-sizing:border-box 用法解析
    浮动塌陷-overflow:hidden来解决
  • 原文地址:https://www.cnblogs.com/duanfu/p/12222603.html
Copyright © 2020-2023  润新知