第十四章 类型信息

 

 

 

package rock.lee.thinkinjava.c14.typeinfo;

import java.util.Arrays;
import java.util.List;

abstract class Shape{
	void draw(){
		System.out.println(this+".daw()");
	}
	abstract public String toString();
}

class Circle extends Shape{
	@Override
	public String toString() {
		return "Circle";
	}
}

class Square extends Shape{
	@Override
	public String toString() {
		return "Square";
	}
}

class Triangle extends Shape{
	@Override
	public String toString() {
		return "Triangle";
	}
}
public class Shapes {
	public static void main(String[] args) {
		//如果没有泛型,默认都会是Object
		List<Shape> shapeList = Arrays.asList(new Circle(),new Square(),new Triangle());
		for (Shape shape : shapeList) {
			shape.draw();//间接调用了toString()
			Class<? extends Shape> c = shape.getClass();
			System.out.println(c.getSuperclass());
			System.out.println(c.getSimpleName());
			System.out.println(c.getCanonicalName());
			System.out.println(c.isInterface());
		}
	}
}
/**
 Circle.daw()
Square.daw()
Triangle.daw()
**/

 

package rock.lee.thinkinjava.c14.typeinfo;

import java.util.Random;

class Initable1{
	//编译期常量
	static final int staticFinal1 = 47;
	//非编译期常量,访问时类要被初始化
	static final int staticFinal2 = ClassInitialization.random.nextInt(1000);
	static{
		System.out.println("Initable1");
	}
}

class Initable2{
	//访问时类要被初始化,只有访问static final声明的常量才不会初始化
	static int staticNonFinal = 147;
	static{
		System.out.println("Initable2");
	}
}

class Initable3{
	static int staticNonFinal = 74;
	static{
		System.out.println("Initable3");
	}
}

public class ClassInitialization {
	static{
		System.out.println("ClassInitialization");
	}
	public static Random random = new Random(47);
	public static void main(String[] args) {
		//does not trigger Initialization
		Class initable1Class = Initable1.class;
		System.out.println("After Creating Initable1 ");
		//does not trigger Initialization
		System.out.println(Initable1.staticFinal1);
		//does  trigger Initialization
		System.out.println(Initable1.staticFinal2);
		//does  trigger Initialization
		System.out.println(Initable2.staticNonFinal);
		try {
			//does  trigger Initialization
			Class initable3Class = Class.forName("rock.lee.thinkinjava.c14.Initable3");
			System.out.println("After Creating Initable3 ");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(Initable3.staticNonFinal);
	}
}
/**
ClassInitialization
After Creating Initable1 
47
Initable1
258
Initable2
147
Initable3
After Creating Initable3 
74
 */

 

你可能感兴趣的:(第十四章 类型信息)