File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -89,7 +89,6 @@ public class Overriding {
8989 public static void main (String [] args) {
9090 Animal a = new Animal();
9191 Animal b = new Horse(); // Animal ref, but a Horse object
92- Horse h = new Horse();
9392
9493 a.eat(); // Runs the Animal version of eat()
9594 b.eat(); // Runs the Horse version of eat()
@@ -105,4 +104,34 @@ Some more rules which may be obvious:
105104* You cannot override a method marked ` final ` .
106105* You cannot override a method marked ` static ` .
107106* If a method can't be inherited, you cannot override it. As said earlier,
108- overriding implies that you're reimplementing a method you inherited.
107+ overriding implies that you're reimplementing a method you inherited.
108+
109+ __ Dynamic Method Invocation:__ Overridden instance methods are dynamically invoked based on the real object's type
110+ rather than the reference type. For example, ` b.eat() ` will actually run the Horse version of ` eat() ` .
111+
112+ -------
113+
114+ ### Q&A
115+
116+ __ Q1.__ Will the below code compile?
117+
118+ {% highlight java linenos %}
119+
120+ class Animal {
121+ public void eat() throws Exception {
122+ // throws an Exception
123+ }
124+ }
125+
126+ class Dog extends Animal {
127+ public void eat() { /* no Exceptions * /}
128+
129+ public static void main(String[] args) {
130+ Animal a = new Dog();
131+ Dog d = new Dog();
132+ d.eat();
133+ a.eat();
134+ }
135+ }
136+
137+ {% endhighlight %}
You can’t perform that action at this time.
0 commit comments