This programming style makes me dizzy

What is the output of this Java program?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.*;
import java.lang.*;
import java.io.*;


class Mammal{ 
    void eat(Mammal m){
        System.out.println("Mammal eats food");
        }
    } 
class Cattle extends Mammal{
    void eat(Cattle c){
        System.out.println("Cattle eats hay"); 
        } 
    }
class Horse extends Cattle{
    void eat(Horse h){
        System.out.println("Horse eats hay"); 
        } 
    } 

public class Main{
    public static void main(String[] args){ 
        Mammal h = new Horse();
        Cattle c = new Horse(); 
        c.eat(h); 
        }
    }


I am not a Java person myself. A friend sent me this. You could help him by adding a solution.

Mammal eats food Cattle eats hay Horse eats hay

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

  • So the first is M a m m a l Mammal reference that points to some instance of H o r s e Horse object.That means that first object named ('h') can access the method in class H o r s e Horse when ever it is called but still refer to M a m m a l Mammal .

  • The second declaration is where C a t t l e Cattle reference points to some instance of H o r s e Horse object. That means simply like in the first , that object named ('c') can access the method from class H o r s e Horse if it is called.

  • So in the example we have call from object reference C a t t l e Cattle where the method has as it's argument reference of class M a m m a l Mammal .

  • By the concept of inheritance when some class B B extends from some class A A , class B B can access all public and protected members and methods.

  • In our example the second object named ('c') must call the method which has as argument reference of class M a m m a l Mammal and it also extends all methods which are public from that class (in our example it inherits the method e a t ( ) eat() where the argument is reference from class M a m m a l Mammal and that method is in class M a m m a l Mammal ) therefore output must be: "Mammal eats food" .

Thanks! I will send this solution to my friend

Agnishom Chattopadhyay - 4 years, 9 months ago

Keep me updated for his response.

Stojan Samojlovski - 4 years, 9 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...