Using this as an example:
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
Is it right here to say upon calling b.move() the method "move() under the Dog class" has overridden the "move() under the Animal class" as the Dog object takes precedence when calling the same method when referenced by an Animal type?
Ive noticed many websites don't explain this, rather they just throw out examples without talking through the stuff line by line. Just want to clear up my terminology confusion.
A side note, would it be possible to have a Dog object but invoke move() which is under the Animal class? for example having something like:
Dog doggy = new Dog();
doggy.move()
>>>
Animals can move
>>>
Would this be possible? would ((Animal) doggy).move() accomplish this?
Absolutely, it is correct to say upon calling b.move() the method "move() under the Dog class" has overridden the "move() under the Animal class".
For the second question, you should implement the class Dog as:
public class Dog extends Animal {
public void move(){
super.move();
}
}
For the third question, the answer is "NO".
((Animal) doggy).move()
This is simply 'redundant' and give the output "move() under the Dog class".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With