package com.ygl;
class Final{
public static final int x=6/3;//此处x在编译时能计算出值,是编译时的常量,则System.out.println(Final.x);直接输出值,不再执行下面static(前提是final)
static{
System.out.println(“Final “);
}
}
public class Test2 {
public static void main(String[] args) {
System.out.println(Final.x);
}
}
//*************************************
2
//======================================
import java.util.Random;
class FinalTest2{
public static final int x=new Random().nextInt(100);//运行时才确定x的值,编译时变量
static{
System.out.println(“FinalTest2”);
}
}
public class Test3 {
public static void main(String[] args) {
System.out.println(FinalTest2.x);
}
}
//****************************************
FinalTest2
10
//**********************************************************
package com.ygl;
class Parent{
static int a=3;
static {
System.out.println(“Parent “);
}
}
class Children extends Parent{
static int b=4;
static{
System.out.println(“Children extends Parent”);
}
}
public class Test4 {
static {
System.out.println(“Test4”);
}
public static void main(String[] args) {
System.out.println(Children.b);
}
}
//********************************
Test4
Parent
Children extends Parent
4
//****************************************
package com.ygl;
class Parent2{
static int a=3;
static {
System.out.println(“Parent “);
}
}
class Children2 extends Parent2{
static int b=4;
static{
System.out.println(“Children extends Parent”);
}
}
public class Test5 {
static {
System.out.println(“Test5”);
}
public static void main(String[] args) {
Parent2 parent;
System.out.println(“————————“);
parent =new Parent2();
System.out.println(Parent2.a);
System.out.println(Children2.b);
}
}
//******************************
Test5
————————
Parent
3
Children extends Parent
4
//*******************************************
package com.ygl;
/**
* 只有当程序访问的静态变量或静态方法确实在当前类或当前接口中定义时,才可以认为是对类或或接口的主动使用
* @author lenovo
*
*/
public class Test6 {
public static void main(String[] args) {
System.out.println(Children3.a);
Children3.doSomething();
}
}
class Parent3{
static int a=3;
static {
System.out.println(“Parent “);
}
static void doSomething(){
System.out.println(“doSomething”);
}
}
class Children3 extends Parent3{
static{
System.out.println(“Children extends Parent”);
}
}
//******************************
Parent
3
doSomething