JAVATM MASTER

When To Cast

Back to Table of Contents

A cast is used to convert an Object of one type to another, but the other type has to be the type it was instantiated from, one of that type's ancestor classes, or one of that type's implemented interfaces.

Here is an example:

class MySuperType {
	public mySuperType(){
	}
	public int add(int i, int j){
		return i + j;
	}
}
class MyExtendingType extends MySuperType{
	public MyExtendingType(){
		super();
	}
	public int subtract(int i, int j){
		returnt i - j;
	}
}
public class myClass{
	//in some method...
	public int demoMethod(){
		MySuperType SType = new MySuperType();
		MyExtendingType EType = new MyExtendingType();
		MySuperType CType = (MySuperType) EType;
/*

SType and CType only have access to the add method and not the subtract method while EType has access to both the add and subtract methods because EType is an instance of MyExtendingType, which extends MySuperType with its add method.

Note that CType refers to the same Object instance that EType refers to because The cast does not instantiate a new Object. Therefore, if you want, you could cast CType back from type MySuperType to MyExtendingType and then you would be able to use both add and subtract methods and not just add.

*/
		//...at the end of that method. 
		MyExtendingType BType = (MyExtendingType) CType;
		return BType.subtract(4, 1);
	}
//returns 3;
	public static void main(String[] args){
		MyClass myDemo = new MyClass();
		int num = myDemo.demoMethod();
		System.out.println("num is: "+num); //prints "num is 3".
	}
}//end of myClass

in the command prompt type:

java MyClass

and it will return: num is 3

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*