Java Object Reference Mechanisms

I’m kind of stuck in the following question:

What two mechanisms of the Java language allow the type of the object reference variable to be "different" than the type of the object to which it refers? Give specific examples to illustrate. In what sense do they not differ at all?

My current answer is that it “implements” and “extends” the right? And they are similar because both of them will make a class that at least will have all the signatures of the superclass method, which can be relevant, abstract, or an interface. It's right? Thanks in advance!

+5
source share
3 answers

. . Java , . ( extends/tools).

. ( Java) . " ".

+3

interface Animal {
   void attackHuman(); // actually public abstract by default
}
class Horse implements Animal {
   public void attackHuman() { }; // must implement
}

// type and reference the same
Horse a1 = new Horse();

// type and reference different
Animal a2 = a1;

class Animal {
   void attackHuman();
}
class Dinosaur extends Animal {
   // attackHuman() inherited
}

// type and reference the same
Dinosaur a1 = new Dinosaur();

// type and reference different
Animal a2 = a1;
+1

. ....

- Animal Super-Class, Dog Cat - inherited .

- , Animal Object Reference Variable.

- Class Polymorphism.

public class Test {

public static void main(String[] args){

Animal a = new Dog();
new Hospital().treatAnimal(a);

   }
}

class Animal {

public void sayIt(){

     }
}

class Dog extends Animal{

public void sayIt(){

    System.out.println("I am Dog");
   }
}


class Cat extends Animal{

public void sayIt(){

System.out.println("I am Cat");
     }
}










See the NEXT PAGE for the Remaining Code

class Hospital{

public void treatAnimal(Animal a){


if(a instanceof Dog){             



   a.sayIt();         // Will output "I am Dog"

  }
else{

a.sayIt();         // Will output "I am Cat"

}


  }

}
0

All Articles