Skip to content

Commit 82afc23

Browse files
author
Ram swaroop
committed
overriding question added
1 parent 70db3c8 commit 82afc23

1 file changed

Lines changed: 31 additions & 2 deletions

File tree

_posts/2015-05-29-overriding.md

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff 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 %}

0 commit comments

Comments
 (0)