๐๐ฎ๐๐ฎ ๐ฅ๐๐ป๐๐ถ๐บ๐ฒ ๐ฃ๐ผ๐น๐๐บ๐ผ๐ฟ๐ฝ๐ต๐ถ๐๐บ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ
Method overriding is more than writing a method in a child class. It connects many Java concepts.
Look at reference types. Dog dog = new Dog(); Dog is the class. dog is the reference. new Dog() is the object.
Now try this: Animal animal = new Dog(); This is upcasting. Java lets you store a child object in a parent reference.
Method overriding happens when a child class changes a parent method. You must follow strict rules.
- Method name must match.
- Parameter count must match.
- Parameter types must match.
- Parameter order must match.
Return types usually match. Java also allows covariant return types. A child class method returns a more specific type.
This creates runtime polymorphism. Animal animal = new Dog(); animal.makeSound();
The compiler sees the reference type. The program sees the object type. Java calls the Dog method during execution.
This is dynamic method dispatch.
- Reference type decides visible methods.
- Object type decides which method runs.
I tested this with an employee system. Employee e1 = new Developer(); Employee e2 = new Tester(); Both use the same reference type. Both run different code.
Overriding is the base for flexible design.