I am familiar with type casting in inheritance model.
Let SuperClass and SubClass be parent and child classes;
SuperClass superClass = new SubClass(); -- Here the object instantiated is a subclass object;
but its reference type is SuperClass; that is only those methods of SuperClass can be called on the subclass object; Any methods that are not inherited/overridden in subclass cannot be called (that is any unique methods of subclass).
I observed same behavior as above if SuperClass is an interface and SubClass implements it. That is only those methods declared in SuperClass interface are available to be called on the SubClass object. Is my understanding correct? But with some casting, I can call methods that is not part of the interface, which I have observed in my sample code below;
I have made some comments on my understanding as how it works; but I would like to know if that make sense or if my interpretation is wrong;
class Animals {
public void bark(){
System.out.println("animal is barking");
}
}
interface catIF {
public void catting();
}
interface dogIF {
public void dogging();
}
class Dog extends Animals implements dogIF {
public void bark(){
System.out.println("dog is barking");
}
public void dogging() {
System.out.println("dogging");
}
}
class Cat extends Animals implements catIF {
public void bark(){
System.out.println("cat is barking");
}
public void catting() {
System.out.println("catting");
}
}
public class Animal {
public static void main(String[] args){
dogIF dog = new Dog();
//dog.bark(); this fails
//This method actually actually exists;
//but it is not available or hidden because dogIF reference
//limits its availability; (this is similar to inheritance)
Dog dog2 = new Dog();
dog2.bark();
////prints dog is barking
Animals an =(Animals) dog;
an.bark();
//prints dog is barking
//by casting we mean, treat the dog as an animals reference
//but the object itself is a dog.
//call the bark() method of dog
//but dog did not have this method in the beginning (see first line
// in main - when instantiated with interface type)
}
}
dogIF#bark()does not exist, so you are right about that. Method invocations are resolved, at compile time, based on the declared type of the reference.checkcast, but the rules are so arcane I've long since forgotten them.)(Animals), eg) then the compiler takes your word for it that the object in question is the type specified. Under the covers acheckcastbytecode assures that what you say is true, but the compiler has no idea whether thecheckcastwill succeed or fail.ClassCastExceptionif it doesn't. So, eitherCatorDogextends/implementsAnimalsand can be cast toAnimals, but they don't have a super/subclass relationship to each other so you can't cast one to the other. Although you could have an object which extendedCatand implementeddogIF, if you wanted to describe a cat that shared the latter behavior with dogs... like mine, which will sometimes retrieve a ball.