@@ -336,13 +336,18 @@ void main() {
336336 <listing xml : id =" animal-dog-example" >
337337 <program language =" java" >
338338 <code >
339+ /**
340+ * Animal class is the superclass, with a method makeSound().
341+ */
339342class Animal {
340-
341343 public void makeSound() {
342344 System.out.println("The animal makes a sound.");
343345 }
344346}
345347
348+ /**
349+ * Dog class is a subclass of Animal, with an additional method bark().
350+ */
346351class Dog extends Animal {
347352 public void bark() {
348353 System.out.println("The dog barks!");
@@ -358,27 +363,37 @@ class Dog extends Animal {
358363 <listing xml : id =" upcasting-example" >
359364 <program interactive =" activecode" language =" java" >
360365 <code >
366+
367+ /**
368+ * Animal class is the superclass, with a method makeSound().
369+ */
361370class Animal {
362371 public void makeSound() {
363372 System.out.println("The animal makes a sound.");
364373 }
365374}
366375
376+ /**
377+ * Dog class is a subclass of Animal, with an additional method bark().
378+ */
367379class Dog extends Animal {
368380 public void bark() {
369381 System.out.println("The dog barks!");
370382 }
371383}
372384
385+ /**
386+ * Upcasting example: A Dog object is created, but the reference is of type Animal.
387+ */
373388void main() {
374389// A Dog object is created, but the reference is of type Animal.
375390// This is implicit upcasting.
376391 Animal myAnimal = new Dog();
377392
378393 myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal.
379394
380- // myAnimal.bark(); // This would cause a compile-time error!
381- // The compiler only knows about the methods in the Animal reference type.
395+ // myAnimal.bark(); // This would cause a compile-time error!
396+ // The compiler only knows about the methods in the Animal reference type.
382397}
383398 </code >
384399 </program >
@@ -393,20 +408,28 @@ void main() {
393408 <listing xml : id =" downcasting-example" >
394409 <program interactive =" activecode" language =" java" >
395410 <code >
411+ /**
412+ * Animal class is the superclass, with a method makeSound().
413+ */
396414class Animal {
397415 public void makeSound() {
398416 System.out.println("The animal makes a sound.");
399417 }
400418}
401419
420+ /**
421+ * Dog class is a subclass of Animal, with an additional method bark().
422+ */
402423class Dog extends Animal {
403424 public void bark() {
404425 System.out.println("The dog barks!");
405426 }
406427}
407428
429+ /**
430+ * Downcasting example: An Animal reference is downcast to a Dog reference after checking its type.
431+ */
408432void main() {
409-
410433 Animal myAnimal = new Dog();
411434
412435 // 'myAnimal' is an Animal reference, but it points to a Dog object.
0 commit comments