Java基础随笔(2)static静态详解

 1 package com.chapter;
 2 
 3 class Bowl {
 4     Bowl(int marker) {
 5         System.out.println("Bowl+(" + marker + ")");
 6     }
 7 
 8     void f1(int marker) {
 9         System.out.println("f1(" + marker + ")");
10     }
11 }
12 
13 class Table {
14     static Bowl bowl1 = new Bowl(1);
15 
16     Table() {
17         System.out.println("Table()");
18         bowl1.f1(1);
19     }
20 
21     void f2(int marker) {
22         System.out.println("f2(" + marker + ")");
23     }
24 
25     static Bowl bowl2 = new Bowl(2);
26 }
27 
28 class Cupboard {
29     static Bowl bowl4 = new Bowl(4);
30 
31     Cupboard() {
32         System.out.println("Cupboard");
33         bowl4.f1(2);
34     }
35 
36     void f3(int marker) {
37         System.out.println("f3(" + marker + ")");
38     }
39     Bowl bowl3 = new Bowl(3);
40 
41     static Bowl bowl5 = new Bowl(5);
42 
43 }
44 
45 
46 public class Demo187 {
47 
48     public static void main(String[] args) {
49         System.out.println("Creating new Cupboard");
50         new Cupboard();
51         System.out.println("Creating new Cupboard");
52 //        table.f2(1);
53 //        cupboard.f3(1);
54     }
55 
56     static Table table = new Table();
57     static Cupboard cupboard = new Cupboard();
58 }
View Code

 

 

 

  •  在方法中存在 static修饰的变量和static块 在进到方法中时会去加载他们,无论是否执行了他们
  • static修饰的变量和static块只会执行一次,即使你后续在访问它也不会再次执行。像上文中的Bowl+(3)就出现了几次就是因为该变量没有被static修饰
  • static修改的值在其他地方只要用上,它的值都是被修改后的值(只要中间程序没有停止)。
posted @ 2023-03-05 20:40  嘿咻噜啦啦  阅读(101)  评论(0)    收藏  举报