If a method or constructor parameter requires an object of a superclass to be passed in when it is invoked, can we send an object with a declared/compile and actual/runtime types of the subclass if we cast the object as the superclass?
ie:
Cat myCat = new Cat();
// Send Animal object as a parameter for a Vet method:
catDoctor.getCheckUp((Animal)myCat);
Hello @nawks22, welcome to the forums! It seems it works with basic types (such as int
, double
, etc). Consider this code:
public static double x(int y){
return y*7;
}
public static void Main(){
System.Console.WriteLine(x((int)7.0)); //<--line 8
System.Console.WriteLine(7.0.GetType()); //logs System.Double
}
Without the (int)
on line 8, the code throws an error, due to the type difference between the required input of x
, and the argument’s type. With the (int)
; however, 49
is printed to the console.