1 package com.jiemyx.oop.demo11; 2 3 public class Student{ 4 public static int age; //静态变量、类变量 5 public double score; //非静态变量 6 7 public static void run(){ 8 9 } 10 11 public void go(){ 12 run(); //静态方法在当前类中还可以直接调用 13 } 14 15 }
package com.jiemyx.oop.demo11; public class Application { public static void main(String[] args) { //属性 System.out.println(Student.age); //静态变量,使用类来直接调用 //System.out.println(Student.score); //报错,score不是静态变量 Student s1 = new Student(); System.out.println(s1.age); System.out.println(s1.score); //非静态变量,需要实例化一个对象来调用 //方法 Student.run(); //静态方法,直接使用类来调用 //Student.go(); //报错 Student s2 = new Student(); s2.run(); s2.go(); } }
1 package com.jiemyx.oop.demo11; 2 3 public class Person { 4 /* 5 { 6 匿名代码块 7 } 8 9 static { 10 静态代码块 11 } 12 */ 13 14 //第二个执行,作用:赋初始值 15 { 16 System.out.println("匿名代码块"); 17 } 18 19 //第一个执行,只执行一次 20 static { 21 System.out.println("静态代码块"); 22 } 23 24 //第三个执行 25 public Person() { 26 System.out.println("构造方法"); 27 } 28 29 public static void main(String[] args) { 30 Person p1 = new Person(); 31 System.out.println("========="); 32 Person p2 = new Person(); 33 } 34 }
运行结果:
静态代码块
匿名代码块
构造方法
=========
匿名代码块
构造方法
1 package com.jiemyx.oop.demo11; 2 3 //静态导入包 4 import static java.lang.Math.random; 5 import static java.lang.Math.PI; 6 7 public final class Test { //有final修饰符的类,不能被其他类继承 8 public static void main(String[] args) { 9 System.out.println(Math.random()); //输出随机数 10 11 //有静态导入包 import static java.lang.Math.random; 可以直接使用random() 12 System.out.println(random()); 13 System.out.println(PI); 14 } 15 }
原文:https://www.cnblogs.com/Jiemyx/p/14682977.html