@@ -249,6 +249,34 @@ something, we just don't know what that something really is). All we can say for
249
249
not the object, but rather a value representing a specific object on the heap. Or ` null ` . When it is ` null ` , i.e,
250
250
` Button b = null; ` you can say that the reference variable ` b ` is not referring to any object.
251
251
252
+ There is one important concept to understand here, i.e, a reference variable can refer to any object that is a
253
+ __ subclass__ of the declared reference variable type but not a __ superclass__ . Let's see why.
254
+
255
+ {% highlight java linenos%}
256
+ class Foo {
257
+ public void doFooStuff() { }
258
+ }
259
+ class Bar extends Foo {
260
+ public void doBarStuff() { }
261
+ }
262
+ class Test {
263
+ public static void main (String [ ] args) {
264
+ Foo reallyABar = new Bar(); // Legal because Bar is a
265
+ // subclass of Foo
266
+ Bar reallyAFoo = new Foo(); // Compiler error! Foo is not a
267
+ // subclass of Bar
268
+ }
269
+ }
270
+ {% endhighlight %}
271
+
272
+ In line 11, ` reallyAFoo ` is a ` Bar ` reference variable (child) so someone would call ` reallyAFoo.doBarStuff() ` but the
273
+ reference variable actually holds a ` Foo ` object (parent) which doesn't have a ` doBarStuff() ` method. So, the compiler
274
+ prevents this and gives a ` Incompatible types ` error.
275
+
276
+ In other words, a child class is nothing but the parent class with additional properties. So there is no issue in line 9,
277
+ where a ` Foo ` reference variable (parent) is holding a ` Bar ` object (child). Because everything a ` Foo ` object can do,
278
+ can also be done by a ` Bar ` object.
279
+
252
280
### Casting
253
281
254
282
__ Casting__ is a way of converting literal values/objects from one type to another. When the type of variable is
0 commit comments