I'm a bit confused about the syntax of typecasting and the creation of objects. Here I have a code of
class OverridingTest{
public static void main(String [] args){
Dog dog = new Hound();
((Hound)dog).sniff();
}
}
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
public void bark(){
System.out.println("bowl");
}
}
I do have some background about the syntax and casting. However, when I tried not casting the "dog" object it sends an error. I'm a bit confused on why the compiler does this.
I read some references about it and saw the syntax behind instantiating objects in the context of casting. It said that in this line of code:
Dog dog = new Hound();
The "Dog" at the start of the line determines the "Type" of the objects. Specifically, it determines the operations the object can perform and the "Hound" which is the subclass of the "Dog" class,is the "Class" and determines the implementation of the methods that are available to the instantiated object.
Now that's the part where I started to get confused. Isn't it the way the "dog" object was instantiated is with reference to the "Hound" class already? Meaning the "dog" object has the implementation of the Hound class and therefore can access it's methods? Why would I need to add typecast operator when accessing its methods? Like this?
((Hound)dog).sniff();
Also, I have another question about it which is kind of a separate question but references of the same code. I tried instantiating the "dog" object with the class reference of the "Dog" class like this.
Dog dog = new Dog();
And then I put it into the subclass of a new line where
Hound newdog = (Hound) dog;
This follows the syntax of typecasting and compiles nicely. However, I get a run time error. Doesn't this follow the methods of casting? If not, how would I do it in another way?