Saturday, May 1, 2010

Java Type system

I was reading Object Oriented design Patterns by Cay Horstmann, notes from this book

Java is a strongly typed language. Most type system rules violations are caught during compilation. In other languages like javascript, applying an operation not suiting the value currently stored in the variable will result in a run time error.
Why compile time checking is safer? Run time checks may pass during testing and fail during deployment when un expected values are stored in those type-less variable.

Every type in java can be anyone below

primitive type
class type
interface type
array type
null type


Type Inquiry

instanceof : Tests whether the type of the object is a subtype of the given type.
getClass(): finds the actual type of the object it refers
if e is a Rectangle, e.getClass().getName() is the string, "java.awt.Rectangle"
For an array type, type of array elements is called the component type of the array
When getClass is applied to an array , it returns an array type and not component type.

string[] s=new String[10];
Class class=s.getClass();
if(class.isArray())
S.o.p("Component type"+c.getComponentType());
//will print "Component Type=String"

No comments:

Post a Comment