Skip to content
This repository was archived by the owner on Feb 10, 2024. It is now read-only.

Commit 5bd464d

Browse files
author
Ram swaroop
committed
added content
1 parent a935100 commit 5bd464d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

_posts/2015-05-14-variables-and-literals.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,34 @@ something, we just don't know what that something really is). All we can say for
249249
not the object, but rather a value representing a specific object on the heap. Or `null`. When it is `null`, i.e,
250250
`Button b = null;` you can say that the reference variable `b` is not referring to any object.
251251

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+
252280
### Casting
253281

254282
__Casting__ is a way of converting literal values/objects from one type to another. When the type of variable is

0 commit comments

Comments
 (0)